2
votes

I have a separate class library that contains a single static class where Im wrapping the use of Log4Net. Something like this (see below).

    public static class Logger
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        static Logger()
        {

            log4net.Config.XmlConfigurator.Configure();
            log = log4net.LogManager.GetLogger(typeof(Logger));
            log.Logger.IsEnabledFor(log4net.Core.Level.All);
        }

        public static void Error(object msg)
        {
            log.Error(msg);
        }

        public static void Error(object msg, Exception ex)
        {
            log.Error(msg, ex);
        }
}

Im having trouble getting anything to be logged. When I step into the code, I see messages on some of the objects such as the ConfigurationMessage:

{log4net:ERROR XmlConfigurator: Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the and elements. The configuration section should look like: }

The assemblyinfo.cs for this class, ive added this

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

So, apparently, it cant find this file? The assembly is being used from an ASP.Net MVC web application and when compiled, the log4net.config gets copied into the /bin folder, so its there, but it cant be found?

1
In a web app, it looks in the root directory, not the bin.dbugger

1 Answers

1
votes

Assembly attribute configuration doesn't play nicely with web apps, especially when the assembly attribute isn't in the primary assembly.

Instead use the overload of XmlConfigurator.Configure that takes a reference to the file itself:

// or wherever your file is
var fileInfo = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); 
if (fileInfo.Exists)
    log4net.Config.XmlConfigurator.Configure(fileInfo);
else 
    throw new InvalidOperationException("No log config file found");