標籤:
1. 首先引入Log4net程式集
2.修改webconfig設定檔
在 configuration 節點下面添加如下節點
<configSections><section name="log4net" type="System.Configuration.IgnoreSectionHandler"/></configSections><log4net><!--定義輸出到檔案中--><appender name="FileAppender" type="log4net.Appender.FileAppender"><!--定義檔案存放位置--><file type="log4net.Util.PatternString" value="Logs\%date{yyyMMddHH}.log"/><appendToFile value="true"/><!--日期格式--><lockingModel type="log4net.Appender.FileAppender+MinimalLock"/><layout type="log4net.Layout.PatternLayout"><!--輸出格式--><conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/></layout></appender><root><!--檔案形式記錄日誌--><appender-ref ref="FileAppender"/></root></log4net>
3.建立 Log4net 協助類
注意需要在
//注意下面的語句一定要加上,指定log4net使用.config檔案來讀取配置資訊//如果是WinForm(假定程式為MyDemo.exe,則需要一個MyDemo.exe.config檔案)//如果是WebForm,則從web.config中讀取相關資訊[assembly: log4net.Config.XmlConfigurator(Watch = true)]namespace qqzssl.Util{ public class Log4NetExport { private static ILog _Ilog = null; private Log4NetExport(Type t) { // 通常情況下,我們通過 LogManager.GetLogger() 來擷取一個記錄器。 // LogManager 內部維護一個 hashtable,儲存新建立 Logger 引用,下次需要時直接從 hashtable 擷取其執行個體。 _Ilog = log4net.LogManager.GetLogger(t); } public static Log4NetExport Create(Type t) { return new Log4NetExport(t); } public void Info(object message) { _Ilog.Info(message); } public void Info(object message, Exception ex) { _Ilog.Info(message, ex); } public void Error(object message) { _Ilog.Error(message); } public void Error(object message, Exception ex) { _Ilog.Error(message, ex); } }}
Log4net 配置注意事項