使用log4net能夠很方便地爲應用添加日誌功能。應用Log4net,開發者能夠很精確地控制日誌信息的輸出,減小了多餘信息,提升了日誌記錄性能。同時,經過外部配置文件,用戶能夠不用從新編譯程序就能改變應用的日誌行爲,使得用戶能夠根據狀況靈活地選擇要記錄的信息。
html
那麼咱們如何在Web項目中使用Log4Net呢?mysql
1、基本配置web
一、下載Log4Net,地址以下:http://logging.apache.org/log4net/download_log4net.cgi,以下圖所示:sql
二、下載到本地後,進行解壓,,並找到對應版本的.NET Framework版本,以下圖所示:數據庫
三、在項目中添加Log4Net.DLL的引用,以下圖所示:apache
四、在Web項目根目錄下建立log4net.config配置文件,以下圖所示:app
配置文件log4new.config XML代碼以下:post
- <?xml version="1.0" encoding="utf-8" ?>
- <log4net debug="false">
- <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
- <param name="File" value="Log/AT.log"/>
- <param name="datePattern" value="YY-MM-dd HH:mm"/>
- <param name="AppendToFile" value="true"/>
- <layout type="log4net.Layout.PatternLayout">
- <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
- </layout>
- </appender>
- <appender name="HttpTraceAppender" type="log4net.Appender.ASPNetTraceAppender">
- <layout type="log4net.Layout.PatternLayout">
- <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
- </layout>
- </appender>
- <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
- <layout type="log4net.Layout.PatternLayout">
- <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
- </layout>
- </appender>
- <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
- <file value="log\AT"/>
- <appendToFile value="true"/>
- <rollingStyle value="Date"/>
- <datePattern value="_yyyyMMdd'.log'"/>
- <staticLogFileName value="false"/>
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%d [%t] %-5p %c - %m%n"/>
- </layout>
- </appender>
- <root>
- <level value="INFO"/>
- <!--<level value="ERROR" />-->
- <appender-ref ref="RollingLogFileAppender"/>
- </root>
- </log4net>
五、項目中添加一個LogHelper.cs操做類,這樣能夠以後的其餘頁面進行調用,以下圖所示:性能
LogHelper.cs類代碼以下:測試
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- [assembly: log4net.Config.XmlConfigurator(Watch = true)]
- namespace APESM_GGJ.CommonClass
- {
- public class LogHelper
- {
- /// <summary>
- /// 輸出日誌到Log4Net
- /// </summary>
- /// <param name="t"></param>
- /// <param name="ex"></param>
- #region static void WriteLog(Type t, Exception ex)
- public static void WriteLog(Type t, Exception ex)
- {
- log4net.ILog log = log4net.LogManager.GetLogger(t);
- log.Error("Error", ex);
- }
- #endregion
- /// <summary>
- /// 輸出日誌到Log4Net
- /// </summary>
- /// <param name="t"></param>
- /// <param name="msg"></param>
- #region static void WriteLog(Type t, string msg)
- public static void WriteLog(Type t, string msg)
- {
- log4net.ILog log = log4net.LogManager.GetLogger(t);
- log.Error(msg);
- }
- #endregion
- }
- }
六、在項目中添加一個全局應用程序類Global.asax,以下圖所示:
方法中添加以下代碼:
- protected void Application_Start(object sender, EventArgs e)
- {
- //應用程序啓動時,自動加載配置log4Net
- XmlConfigurator.Configure();
- }
七、打開Web.config文件,添加以下配置信息,以下圖所示:
配置文件代碼以下:
- <?xml version="1.0" encoding="utf-8"?>
- <!--
- 有關如何配置 ASP.NET 應用程序的詳細信息,請訪問
- http://go.microsoft.com/fwlink/?LinkId=169433
- -->
- <configuration>
- <configSections>
- <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
- </configSections>
- <log4net configSource="log4net.config"/>
- <system.web>
- <httpModules>
- <!--重寫IHttpModule類,須要配置的信息-->
- <!--<add name="FilterModule" type="APESM_GGJ.FilterModule,APESM_GGJ" />-->
- </httpModules>
- <compilation debug="true" targetFramework="4.0" />
- </system.web>
- </configuration>
八、在頁面中調用,進行日誌寫入,以下圖所示:
頁面調用代碼:
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- LogHelper.WriteLog(typeof(Login), "測試在Web項目中使用Log4Net日誌!");
- }
- }
九、查看項目根目錄下的Log文件夾,能夠看見咱們寫入的日誌log文件,以下圖所示:
至此在Web項目中使用Log4Net進行日誌記錄的功能就已經實現了。
---------------------------------------------------------------------------------------------------------------------
2、擴展
上面實現的是將日誌寫入到文件中,那麼若是想寫入到數據庫中,該如何操做,這裏以SQL Server爲例,建立一個日誌表,而後修改log4net.config文件,以下代碼:
- <?xml version="1.0" encoding="utf-8" ?>
- <log4net debug="false">
- <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
- <bufferSize value="10" />
- <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
- <connectionString value="DATABASE=CSDN;SERVER=.;UID=sa;PWD=111111;Connect Timeout=15;" />
- <commandText value="INSERT INTO ErrorLog ([dtDate],[sThread],[sLevel],[sLogger],[sMessage],[sException]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
- <parameter>
- <parameterName value="@log_date" />
- <dbType value="DateTime" />
- <layout type="log4net.Layout.RawTimeStampLayout" />
- </parameter>
- <parameter>
- <parameterName value="@thread" />
- <dbType value="String" />
- <size value="100" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%t" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@log_level" />
- <dbType value="String" />
- <size value="200" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%p" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@logger" />
- <dbType value="String" />
- <size value="500" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%logger" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@message" />
- <dbType value="String" />
- <size value="3000" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%m" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@exception" />
- <dbType value="String" />
- <size value="4000" />
- <layout type="log4net.Layout.ExceptionLayout" />
- </parameter>
- </appender>
- <!-- setup the root category, add the appenders and set the default level -->
- <root>
- <level value="WARN"/>
- <level value="INFO"/>
- <level value="DEBUG"/>
- <level value="FINE"/>
- <appender-ref ref="ADONetAppender" />
- </root>
- <!-- specify the level for some specific categories -->
- <logger name="iNotes">
- <level value="WARN"/>
- <level value="INFO"/>
- <level value="DEBUG"/>
- <level value="FINE"/>
- <appender-ref ref="ADONetAppender"/>
- </logger>
- <logger name="StellaLogger">
- <level value="ALL"/>
- <appender-ref ref="AdoNetAppender" />
- </logger>
- </log4net>
注意 <bufferSize value="10" /> ,須要注意的一個參數 bufferSize=10 表示是記錄10 條到緩衝區,滿10條後再寫入SQL server;
測試時將其修改成1
生產環境建議100
上面配置節中數據庫名,用戶名和密碼,根據實際狀況進行修改。
數據庫表ErrorLog建立語句爲:
- CREATE TABLE ErrorLog(
- nId bigint IDENTITY(1,1) NOT NULL,
- dtDate datetime NOT NULL,
- sThread nvarchar(100) NOT NULL,
- sLevel nvarchar(200) NOT NULL,
- sLogger nvarchar(500) NOT NULL,
- sMessage nvarchar(3000) NOT NULL,
- sException nvarchar(4000) NULL
- );
以下圖所示:
3、整合
想同時保存到日誌文件和數據庫,log4net.config的文件配置以下XML代碼所示:
- <?xml version="1.0" encoding="utf-8" ?>
- <log4net debug="false">
- <!-- 將日誌信息寫入SQL Server數據庫 2015-09-29-->
- <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
- <bufferSize value="1" />
- <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
- <connectionString value="DATABASE=CSDN;SERVER=.;UID=sa;PWD=111111;Connect Timeout=15;" />
- <commandText value="INSERT INTO ErrorLog ([dtDate],[sThread],[sLevel],[sLogger],[sMessage],[sException]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
- <parameter>
- <parameterName value="@log_date" />
- <dbType value="DateTime" />
- <layout type="log4net.Layout.RawTimeStampLayout" />
- </parameter>
- <parameter>
- <parameterName value="@thread" />
- <dbType value="String" />
- <size value="100" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%t" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@log_level" />
- <dbType value="String" />
- <size value="200" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%p" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@logger" />
- <dbType value="String" />
- <size value="500" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%logger" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@message" />
- <dbType value="String" />
- <size value="3000" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%m" />
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@exception" />
- <dbType value="String" />
- <size value="4000" />
- <layout type="log4net.Layout.ExceptionLayout" />
- </parameter>
- </appender>
- <!-- 將日誌信息寫入到項目日誌文件 2015-09-29 -->
- <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
- <param name="File" value="Log/AT.log"/>
- <param name="datePattern" value="YY-MM-dd HH:mm"/>
- <param name="AppendToFile" value="true"/>
- <layout type="log4net.Layout.PatternLayout">
- <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
- </layout>
- </appender>
- <appender name="HttpTraceAppender" type="log4net.Appender.ASPNetTraceAppender">
- <layout type="log4net.Layout.PatternLayout">
- <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
- </layout>
- </appender>
- <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
- <layout type="log4net.Layout.PatternLayout">
- <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
- </layout>
- </appender>
- <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
- <file value="log\AT"/>
- <appendToFile value="true"/>
- <rollingStyle value="Date"/>
- <datePattern value="_yyyyMMdd'.log'"/>
- <staticLogFileName value="false"/>
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%d [%t] %-5p %c - %m%n"/>
- </layout>
- </appender>
- <!--設置根目錄,添加appenders並設置默認日誌等級 -->
- <root>
- <level value="WARN"/>
- <level value="INFO"/>
- <level value="DEBUG"/>
- <level value="FINE"/>
- <appender-ref ref="ADONetAppender" />
- <appender-ref ref="RollingLogFileAppender"/>
- </root>
- <!-- 爲特定的目錄指定等級 -->
- <logger name="iNotes">
- <level value="WARN"/>
- <level value="INFO"/>
- <level value="DEBUG"/>
- <level value="FINE"/>
- <appender-ref ref="ADONetAppender"/>
- <appender-ref ref="RollingLogFileAppender"/>
- </logger>
- <logger name="StellaLogger">
- <level value="ALL"/>
- <appender-ref ref="AdoNetAppender" />
- <appender-ref ref="RollingLogFileAppender"/>
- </logger>
- </log4net>