C#在window服務配置Log4Net.dll
阿新 • • 發佈:2019-01-05
1.使用背景:
C#window服務下新增一個日誌記錄程式集(Log4Net.dll)
2.新增和使用步驟如下:
一、下載並引入Log4Net.dll程式集到專案中
下載地址:http://logging.apache.org/log4net/download_log4net.cgi
二、在App.Config中新增對應的節點
<!--重點configsections必須是第一個節點1og4net配置--> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections>
三、在App.Config中新增Log4Net.dll初始化資訊(主要一些按照什麼格式儲存,儲存位置的配置)
<log4net> <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL --> <!-- Set root logger level to ERROR and its appenders --> <root> <level value="ALL" /> <appender-refref="SysAppender" /> </root> <!-- Print only messages of level DEBUG or above in the packages --> <logger name="WebLogger"> <level value="DEBUG" /> </logger> <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net"> <!--日誌資料夾名稱--> <param name="File" value="ProJectsLogs/" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value=""Logs_"yyyyMMdd".txt"" /> <param name="StaticLogFileName" value="false" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> </layout> </appender> <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net"> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> </layout> </appender> </log4net>
四、在AssemblyInfo.cs:配置檔案中讀取配置Log4net.dll
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
五、使用Log4Net.Dll記錄日誌
//首先例項化Log4net private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //使用記錄資訊 log.Debug("Debug", new Exception("Debug")); log.Info("Info", new Exception("Info")); log.Warn("Warn", new Exception("Warn")); log.Error("Error", new Exception("Error")); log.Fatal("Fatal", new Exception("Fatal"));