博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
log4net的相关使用笔记
阅读量:5945 次
发布时间:2019-06-19

本文共 7041 字,大约阅读时间需要 23 分钟。

1, XmlConfigurator

创建添加一个Tracer project,引用nuget上最新的log4net

在Tracer里新增一个AppLog类:

public static class AppLog    {        private static ILog log;        static AppLog()        {            string path = System.IO.Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "log4net.config");            XmlConfigurator.ConfigureAndWatch(new FileInfo(path));            log = LogManager.GetLogger(typeof(AppLog));            WriteHeaderInfo();        }        public static void Debug(object message)        {            log.Debug(message);        }        public static void Debug(string format, params object[] args)        {            log.DebugFormat(format, args);        }        public static void Info(object message)        {            log.Info(message);        }        public static void Info(string format, params object[] args)        {            log.InfoFormat(format, args);        }        public static void Warn(object message)        {            log.Warn(message);        }        public static void Warn(object message, Exception exception)        {            log.Warn(message, exception);        }        public static void WarnFormatted(string format, params object[] args)        {            log.WarnFormat(format, args);        }        public static void Error(object message)        {            log.Error(message);        }        public static void Error(object message, Exception exception)        {            log.Error(message, exception);        }        public static void ErrorFormatted(string format, params object[] args)        {            log.ErrorFormat(format, args);        }        public static void Fatal(object message)        {            log.Fatal(message);        }        public static void Fatal(object message, Exception exception)        {            log.Fatal(message, exception);        }        public static void FatalFormatted(string format, params object[] args)        {            log.FatalFormat(format, args);        }        ///         /// Write the logging header, e.g. some system informations        ///         /// 
private static void WriteHeaderInfo() { System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly(); System.Version appVersion = myAssembly.GetName().Version; string strDomainName = string.Empty; string strUserName = string.Empty; string OSType = Is64BitWindowsOS() ? "64-bit" : "32-bit"; FileInfo file = new FileInfo(myAssembly.Location); string createDate = file.CreationTime.ToString("yyyy-MM-dd HH:mm:ss"); log.Info("=============================================================================================================="); log.Info(string.Empty); log.Info(string.Format("\t[Version: {0}] Logging started at {1}", appVersion.ToString(), System.DateTime.Now.ToString())); log.Info(string.Empty); log.Info(string.Format("\tOS Version: {0}({1})\tCLR Version: {2}", System.Environment.OSVersion.ToString(), OSType, System.Environment.Version.ToString())); log.Info(string.Format("\tLanguage: {0}\tUI Language: {1}", System.Threading.Thread.CurrentThread.CurrentCulture.DisplayName, System.Threading.Thread.CurrentThread.CurrentUICulture.DisplayName)); log.Info(string.Format("\tUser Domain: {0}\tUsername(Local Session): {1}", System.Environment.UserDomainName, System.Environment.UserName)); log.Info(string.Format("\tUser Domain: {0}\tUsername(Network Session): {1}", strDomainName, strUserName)); log.Info(string.Format("\tBuild Created Time: {0}", createDate)); log.Info(string.Empty); log.Info("=============================================================================================================="); log.Info(string.Empty); } private static bool Is64BitWindowsOS() { bool is64Bit = false; try { string cpuType = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); string originalCpuTypeOr = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"); if (string.Compare(cpuType, "amd64", true) == 0 || string.Compare(originalCpuTypeOr, "amd64", true) == 0) { is64Bit = true; } else { is64Bit = false; } } catch (System.Security.SecurityException e) { System.Diagnostics.Debug.Fail("Cannot detect the process bitness\n" + e.ToString()); } catch (Exception ex) { System.Diagnostics.Debug.Fail("Cannot detect the process bitness\n" + ex.ToString()); } return is64Bit; } }

在Tracer里创建一个log4net.config文件,并且确定这个文件在编译的时候会复制到对应文件夹

这样,当其他app想写log,只需要调用AppLog的相关静态方法。

Tracer.AppLog.Debug("User calls method...Interval:{0}ms", Interval);Tracer.AppLog.Debug("Start!");

 

 

2, BasicConfigurator

log4net也支持不用config文件的方式

比如,在上面的例子,我们可以不创建log4net.config文件,并且将AppLog的静态创建方法改写如下:

static AppLog()        {            PatternLayout layout = new PatternLayout("%date{MMM/dd/yyyy HH:mm:ss,fff} [%thread] %-5level %logger %ndc – %message%newline");            LevelMatchFilter filter = new LevelMatchFilter();            filter.LevelToMatch = Level.All;            filter.ActivateOptions();            RollingFileAppender appender = new RollingFileAppender();            appender.File = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "common.log");            appender.ImmediateFlush = true;            appender.AppendToFile = true;            appender.RollingStyle = RollingFileAppender.RollingMode.Date;            appender.DatePattern = "-yyyy-MM-dd";            appender.LockingModel = new FileAppender.MinimalLock();            appender.Name = string.Format("{0}Appender", "AppLog");            appender.AddFilter(filter);            appender.Layout = layout;            appender.ActivateOptions();            string repositoryName = string.Format("{0}Repository", "AppLog");            ILoggerRepository repository = LoggerManager.CreateRepository(repositoryName);            string loggerName = string.Format("{0}Logger", "AppLog");            BasicConfigurator.Configure(repository, appender);            log = LogManager.GetLogger(repositoryName, loggerName);//这是重点            WriteHeaderInfo();        }

 

 

参考文章:

转载于:https://www.cnblogs.com/AlvinLiang/p/8073815.html

你可能感兴趣的文章
python-while循环
查看>>
手机端上传图片及java后台接收和ajaxForm提交
查看>>
【MSDN 目录】C#编程指南、C#教程、ASP.NET参考、ASP.NET 4、.NET Framework类库
查看>>
jquery 怎么触发select的change事件
查看>>
angularjs指令(二)
查看>>
<气场>读书笔记
查看>>
领域驱动设计,构建简单的新闻系统,20分钟够吗?
查看>>
web安全问题分析与防御总结
查看>>
React 组件通信之 React context
查看>>
Linux下通过配置Crontab实现进程守护
查看>>
ios 打包上传Appstore 时报的错误 90101 90149
查看>>
Oracle推出轻量级Java微服务框架Helidon
查看>>
密码概述
查看>>
jQuery的技巧01
查看>>
基于泛型实现的ibatis通用分页查询
查看>>
gopacket 使用
查看>>
AlertDialog对话框
查看>>
我的友情链接
查看>>
linux安全---cacti+ntop监控
查看>>
鸟哥的linux私房菜-shell简单学习-1
查看>>