asp.net Web專案中使用Log4Net進行錯誤日誌記錄

暖楓無敵發表於2015-09-29

    使用log4net可以很方便地為應用新增日誌功能。應用Log4net,開發者可以很精確地控制日誌資訊的輸出,減少了多餘資訊,提高了日誌記錄效能。同時,通過外部配置檔案,使用者可以不用重新編譯程式就能改變應用的日誌行為,使得使用者可以根據情況靈活地選擇要記錄的資訊。


   那麼我們如何在Web專案中使用Log4Net呢?


一、基本配置


1、下載Log4Net,地址如下:http://logging.apache.org/log4net/download_log4net.cgi,如下圖所示:


      

2、下載到本地後,進行解壓,,並找到對應版本的.NET Framework版本,如下圖所示:




3、在專案中新增Log4Net.DLL的引用,如下圖所示:




4、在Web專案根目錄下建立log4net.config配置檔案,如下圖所示:



配置檔案log4new.config XML程式碼如下:

<?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>

 

5、專案中新增一個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

    }
}


 6、在專案中新增一個全域性應用程式類Global.asax,如下圖所示:




 方法中新增如下程式碼:

protected void Application_Start(object sender, EventArgs e)
{
     //應用程式啟動時,自動載入配置log4Net
     XmlConfigurator.Configure();
 }



 7、開啟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>


 8、在頁面中呼叫,進行日誌寫入,如下圖所示:



頁面呼叫程式碼:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LogHelper.WriteLog(typeof(Login), "測試在Web專案中使用Log4Net日誌!");
    }
}


9、檢視專案根目錄下的Log資料夾,可以看見我們寫入的日誌log檔案,如下圖所示:



   至此在Web專案中使用Log4Net進行日誌記錄的功能就已經實現了。


---------------------------------------------------------------------------------------------------------------------


二、擴充套件


    上面實現的是將日誌寫入到檔案中,那麼如果想寫入到資料庫中,該如何操作,這裡以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
);

如下圖所示:




三、整合

想同時儲存到日誌檔案和資料庫,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>


===========================================================================

如果覺得對您有幫助,微信掃一掃支援一下:



相關文章