log4net set from an external config file not working

Matt Roberts picture Matt Roberts · Jun 22, 2011 · Viewed 7.2k times · Source

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.

Answer

Eben Roux picture Eben Roux · Jun 22, 2011

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.