C# 使用/配置Log4Net
阿新 • • 發佈:2018-12-21
1、首先在專案中新增Nuget程式包...
2、然後在NuGet窗體中搜索Log4Net,然後點選安裝<安裝過程可能會持續幾分鐘,請耐心等待>
3、在專案中新增一個Config檔案,如已有App.config,則直接在其中新增內容:
截圖中配置的XML程式碼如下:
<log4net> <logger name="logerror"> <level value="ERROR" /> <appender-ref ref="ErrorAppender" /> </logger> <logger name="loginfo"> <level value="INFO" /> <appender-ref ref="InfoAppender" /> </logger> <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Log\\LogError\\" /> <param name="AppendToFile" value="true" /> <param name="MaxSizeRollBackups" value="100" /> <param name="MaxFileSize" value="10240" /> <param name="StaticLogFileName" value="false" /> <param name="DatePattern" value="yyyyMMdd".txt"" /> <param name="RollingStyle" value="Date" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%n異常時間:%d %n異常級別:%-5p%n異常內容:%m%n" /> </layout> <!--< > = <> %n = 回車--> </appender> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Log\\LogInfo\\" /> <param name="AppendToFile" value="true" /> <param name="MaxFileSize" value="10240" /> <param name="MaxSizeRollBackups" value="100" /> <param name="StaticLogFileName" value="false" /> <param name="DatePattern" value="yyyyMMdd".txt"" /> <param name="RollingStyle" value="Date" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="日誌時間:%d %n日誌級別:%-5p %n日誌內容:%m%n%n" /> </layout> </appender> </log4net>
最後在專案的 AssemblyInfo.cs 檔案中註冊Config檔案,如下:
//為專案註冊Log4Net.config配置檔案 [assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
最後,新增日誌類:
public class LogHelper { private LogHelper() { } public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo"); public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror"); public static void SetConfig() { log4net.Config.XmlConfigurator.Configure(); } public static void SetConfig(FileInfo configFile) { log4net.Config.XmlConfigurator.Configure(configFile); } public static void WriteLog(string info) { if (loginfo.IsInfoEnabled) { loginfo.Info(info); } } public static void WriteLog(string info, Exception se) { if (logerror.IsErrorEnabled) { logerror.Error(info, se); } } }
好了,到了這裡,準備工作也就完成了,下面我們就開始測試下吧
日誌檔案預設記錄在根目錄下,在config中可以更改路徑
如果這篇文章對你有幫助的話,評論或推薦下吧!(轉載請註明原作者!)