Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

c# - log4net set from an external config file not working

I'm having a weird issue with log4net.

In an ASP.NET application, I want to configure log4net externally, so I have a separate log4net.config file which I hook up to my web app with this line in the AssemblyInfo.cs file belonging to my web app:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]

Now, if I instantiate the log4net logger class the normal way like this:

public class MyClass
{
    private static readonly ILog _logger = log4net.LogManager.GetLogger(typeof(MyClass));
    ....

Then this works, and the logging works as normal. However, I've wrapped my logging code in a LogManager class, which is part of a separate assembly (Infrastructure), and is reused across a number of projects. It has a GetLogger that looks like this:

public static class LogManager
{
    public static ILog GetLogger()
    {
        var stack = new StackTrace();
        var frame = stack.GetFrame(1);
        return new log4net.LogManager.GetLogger(frame.GetMethod().DeclaringType);
    }
}

So I can use this in my asp.net code:

public class MyClass
{
    private static readonly ILog _logger = LogManager.GetLogger();
    ....

But... This doesn't work! No logging is produced It doesn't seem to hook up the config file correctly. If I put my log4net config directly into the web.config, then this LogManager works fine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To sum up what Bibhu has said. It has all to do with log4net.Config.XmlConfigurator.

You have to configure log4net before logging will start. So whenever you use your LogManager class the hosting application (windows, web) must configure the logging.

Either that or you need to do it in your LogManager.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...