通过log4net来记录系统日志、异常...是非常方便的,自己可以定义文件保存路径、文件大小、内容格式等等,网上也有很多关于log4net的使用讲解,大家可以去http://logging.apache.org/log4net/看关于log4net更详细的介绍(没啥好讲的,我也将不明白,写此文只是做个笔记,方便自己用的时候拷贝)
下面看使用三重奏
我一般用log4net用来记录一些用户操作,和异常,所以只用到INFO和ERROR
1 <configSections> 2 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> 3 </configSections> 4 <log4net> 5 <root> 6 <level value="All"/> 7 <appender-ref ref="LogFileAppender"/> 8 <appender-ref ref="ErrorFileAppender"/> 9 </root> 10 11 <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" LEVEL="INFO"> 12 <param name="File" value="Logs\info\"/> 13 <param name="AppendToFile" value="true"/> 14 <param name="MaxSizeRollBackups" value="-1"/> 15 <param name="MaximumFileSize" value="10MB"/> 16 <param name="DatePattern" value="yyyy-MM-dd.'.txt'"/> 17 <param name="RollingStyle" value="Date"/> 18 <param name="StaticLogFileName" value="false"/> 19 <layout type="log4net.Layout.PatternLayout"> 20 <param name="ConversionPattern" value="记录时间:%date 线程ID:[%thread] 日志级别:%-5level 类:%logger property:[%property{NDC}] - 描述:%message%newline"/> 21 </layout> 22 <filter type="log4net.Filter.LevelRangeFilter"> 23 <param name="LevelMin" value="INFO"/> 24 <param name="LevelMax" value="INFO"/> 25 </filter> 26 </appender> 27 <appender name="ErrorFileAppender" type="log4net.Appender.RollingFileAppender" LEVEL="ERROR"> 28 <param name="File" value="Logs\error\"/> 29 <param name="AppendToFile" value="true"/> 30 <param name="MaxSizeRollBackups" value="-1"/> 31 <param name="MaximumFileSize" value="10MB"/> 32 <param name="DatePattern" value="yyyy-MM-dd.'.txt'"/> 33 <param name="RollingStyle" value="Date"/> 34 <param name="StaticLogFileName" value="false"/> 35 <layout type="log4net.Layout.PatternLayout"> 36 <param name="ConversionPattern" value="记录时间:%date 线程ID:[%thread] 日志级别:%-5level 类:%logger property:[%property{NDC}] - 描述:%message%newline"/> 37 </layout> 38 <filter type="log4net.Filter.LevelRangeFilter"> 39 <param name="LevelMin" value="ERROR"/> 40 <param name="LevelMax" value="ERROR"/> 41 </filter> 42 </appender> 43 </log4net>
1 [assembly: log4net.Config.XmlConfigurator(Watch = true)]
为了省事,我建了个log4net的帮助类
1 public sealed class Log4netHelper<T> where T : class 2 { 3 private static log4net.ILog logger; 4 private static readonly object padlock = new object(); 5 6 Log4netHelper() 7 { 8 9 } 10 11 public static log4net.ILog Logger 12 { 13 get 14 { 15 if (logger == null) 16 { 17 lock (padlock) 18 { 19 if (logger == null) 20 { 21 logger = log4net.LogManager.GetLogger(typeof(T)); 22 } 23 } 24 } 25 return logger; 26 } 27 } 28 29 }
配置完了,现在就开始随便调了
请慎重使用以上代码,以免造成误导,当中若有错误(代码习惯、规范、语法等等),我很乐意听取您的建议和指导