How do you configure and enable log4net for a stand-alone class library assembly?

前端 未结 6 1244
走了就别回头了
走了就别回头了 2020-12-13 04:02

Background

I am writing a class library assembly in C# .NET 3.5 which is used for integration with other applications including third-party Commercial-Off-The-Shel

6条回答
  •  庸人自扰
    2020-12-13 04:55

    You can probably code something around the XmlConfigurator class:

    public static class MyLogManager
    {
        // for illustration, you should configure this somewhere else...
        private static string configFile = @"path\to\log4net.config";
    
        public static ILog GetLogger(Type type)
        {
            if(log4net.LogManager.GetCurrentLoggers().Length == 0)
            {
                // load logger config with XmlConfigurator
                log4net.Config.XmlConfigurator.Configure(configFile);
            }
            return LogManager.GetLogger(type);
        }
    }
    

    Then in your classes, instead of:

    private static readonly ILog log = LogManager.GetLogger(typeof(MyApp));
    

    Use:

    private static readonly ILog log = MyLogManager.GetLogger(typeof(MyApp));
    

    Of course, it would be preferable to make this class a service and dynamically configure it with the IoC container of your choice, but you get the idea?

    EDIT: Fixed Count() problem pointed out in comments.

提交回复
热议问题