通過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 }
配置完了,現在就開始隨便調了
請慎重使用以上代碼,以免造成誤導,當中若有錯誤(代碼習慣、規范、語法等等),我很樂意聽取您的建議和指導