log4net教程日志分类和自动维护示例

如果我们需要通过配置不同的ILog,流程是这样的,首先要创建一个ILoggerRepository,通过它来进行日志等级的配置,和各种Appender,接着通过LogManager在ILoggerRepository获取一个Ilog对象,就可以写日志了。代码如下:

复制代码 代码如下:


public static ILog GetLogger(string repositoryName = "")
        {
            if (string.IsNullOrEmpty(repositoryName)) return LogManager.GetLogger("Defalut");

ILoggerRepository repository = null;
            try
            {
                repository = LogManager.GetRepository(repositoryName);
            }
            catch (Exception) { }

//找到直接返回ilog
            if (repository != null)
                return LogManager.GetLogger(repositoryName, "Defalut");

//未找到则创建,多线程下很有可能创建时,就存在了
            try
            {
                repository = LogManager.CreateRepository(repositoryName);
            }
            catch (Exception)
            {
                repository = LogManager.GetRepository(repositoryName);
            }

//配置日志等级  读取Appsettings默认配置 
            var appSet = ConfigurationManager.AppSettings.AllKeys;

//查找日志等级
            const string logLevel = "LogLevel";
            var hasSettings = Array.IndexOf(appSet, logLevel);
            if (hasSettings > -1)
            {
                var level = ConfigurationManager.AppSettings[logLevel].ToLower();
                if (level == "all") repository.Threshold = Level.All;
                else if (level == "debug") repository.Threshold = Level.Debug;
                else if (level == "info") repository.Threshold = Level.Info;
                else if (level == "warn") repository.Threshold = Level.Warn;
                else if (level == "error") repository.Threshold = Level.Error;
                else if (level == "fatal") repository.Threshold = Level.Fatal;
                else if (level == "off") repository.Threshold = Level.Off;
            }
            else repository.Threshold = Level.All;

//查找输出Appender
            const string logAppender = "LogAppender";
            hasSettings = Array.IndexOf(appSet, logAppender);
            if (hasSettings > -1)
            {
                var appenders = ConfigurationManager.AppSettings[logAppender].ToLower().Split(',');
                foreach (var appender in appenders)
                {
                    if (appender == "rollingfile") LoadRollingFileAppender(repository);
                    else if (appender == "console") LoadConsoleAppender(repository);
                    else if(appender == "trace") LoadTraceAppender(repository);
                }
            }
            else LoadRollingFileAppender(repository);

return LogManager.GetLogger(repositoryName, "Default");
        }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjzsfj.html