天天看點

使用log4net記錄日志到資料庫(含有自定義屬性)

記錄日志是管理系統中對使用者行為的一種監控與稽核,asp.net中記錄日志的方式有很多種,這裡我隻介紹一下最近用到的log4net,關于他的具體介紹網上有很多,我講一下他的用法。

第一步:在配置檔案中的<configSections>節添加下面一句話

               <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

第二步:在<configuration>節中添加如下内容

 < log4net>

  <root >

   <level value="Debug"/>

   <appender-ref ref="ADONetAppender"/>

  </root>

  <logger name="myLogger">

      <level value="Debug"/>

      <appender-ref ref="ADONetAppender"/>

    </logger>

//關于上邊root到logger這塊,如果同時出現,有可能會出現重複插入記錄的情況,那麼就需要改一下代碼,把上面兩段代碼改成如下一段代碼,如下:

   <level value="Debug" name="myLogger"/>

//下面就是對插入到資料庫一些基本設定和基本字段設定

  <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender,log4net">

   <!--BufferSize為緩沖區大小,隻有日志記錄超10條才會一塊寫入到資料庫-->

   <bufferSize value="10"/>

   <!--或寫為<param name="BufferSize" value="10" />-->

   <!--引用-->

   <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>

   <!--連接配接資料庫字元串-->

   <connectionString value="Data Source=.;Initial Catalog=audit;Persist Security Info=True;User ID=sa;Password=123;MultipleActiveResultSets=True"/>

   <!--插入到表Log-->

      <commandText value="INSERT INTO T_AUDITINFO ([EVENTTYPE],[TIMESTAMP],[EVENTCATEGORY],[EVENT_ID],[COMPUTERNAME],[MAC_ADDRESS],[USERNAME],[SOURCETYPE],[SOURCE],[DESCRIPTION],[COLLECTDATE]) VALUES (@Event_Type,@log_date, @EventCategory, @Event_ID, @ComputerName,@Mac_Address,@UserName,@SourceType,@Source,@Description,@CollectDate)"/>

   <!--日志類型,這裡均為3-->

   <parameter>

    <parameterName value="@Event_Type"/>

    <dbType value="Int32"/>

    <layout type="LogComponent.MyLayout, LogComponent">

     <param name="ConversionPattern" value="%property{Event_Type}"/>//注意這裡,當用到property時,就表明這是使用者自定義的字段屬性啦,是log4net中所沒有提供的字段。其中MyLayout是自定義屬性所在的類,

LogComponent是類所在的命名空間,這是我們自己要寫的部分,将在下面介紹。

    </layout>

   </parameter>

   <!--日志記錄時間,RawTimeStampLayout為預設的時間輸出格式 -->

    <parameterName value="@log_date"/>

    <dbType value="DateTime"/>

    <layout type="log4net.Layout.RawTimeStampLayout"/>//這裡呢是擷取log4net中提供的日志時間

   <!--日志分類描述-->

    <parameterName value="@EventCategory"/>

    <dbType value="String"/>

    <size value="50"/>

     <param name="ConversionPattern" value="%property{EventCategory}"/>

   <!--日志分類号-->

    <parameterName value="@Event_ID"/>

     <param name="ConversionPattern" value="%property{Event_ID}"/>

   <!--計算機IP-->

    <parameterName value="@ComputerName"/>

     <param name="ConversionPattern" value="%property{ComputerName}"/>

   <!--計算機Mac資訊-->

    <parameterName value="@Mac_Address"/>

     <param name="ConversionPattern" value="%property{Mac_Address}"/>

   <!--登陸系統使用者名-->

    <parameterName value="@UserName"/>

     <param name="ConversionPattern" value="%property{UserName}"/>

   <!--事件來源類型,這裡預設為Rier-->

    <parameterName value="@SourceType"/>

    <size value="20"/>

     <param name="ConversionPattern" value="%property{SourceType}"/>

  <!--事件來源-->

    <parameterName value="@Source"/>

     <param name="ConversionPattern" value="%property{Source}"/>

   <!--事件描述-->

    <parameterName value="@Description"/>

    <size value="500"/>

     <param name="ConversionPattern" value="%property{Description}"/>

   <!--日志收集時間-->

    <parameterName value="@CollectDate"/>

    <layout type="log4net.Layout.RawTimeStampLayout"/>

        </appender>

      </log4net>

//部落格出處有人引用後無法寫入日志,于是可以将配置修改如下

1

2

3

4

5

6

7

<parameter>

<parameterName value=

"@Event_Type"

/>

<dbType value=

"Int32"

/>

<layout type=

"LogComponent.MyLayout, LogComponent"

>

//這裡修改

<param name=

"ConversionPattern"

value=

"%property{Event_Type}"

/>

</layout>

</parameter>

改為

<parameter>

<parameterName value=

"@Event_Type"

/>

<dbType value=

"Int32"

/>

<layout type=

"LogComponent.MyLayout"

>

<param name=

"ConversionPattern"

value=

"%property{Event_Type}"

/>

</layout>

</parameter>

第三步:自定義類,這些類呢包含将要插入資料庫中的自定義字段

命名空間為 LogComponent 包含3個類:LogContent.cs、 MyLayout.cs 、MyMessagePatternConverter .cs

第一個類 LogContent.cs 包含了所有的自定字段屬性

using System;

using System.Data;

using System.Configuration;

using System.Web;

/// <summary>

/// LogContent 的摘要說明

/// </summary>

public class LogContent

{

    public LogContent(int eventType,string eventCategory,int eventID,string computerName,string macAddress,string userName,string sourceType,string source,string description)

    {

        _event_Type = eventType;

        _eventCategory = eventCategory;

        _event_ID = eventID;

        _computerName = computerName;

        _mac_Address = macAddress;

        _userName = userName;

        _sourceType = sourceType;

        _source = source;

        _description = description;

    }

    int _event_Type;

    /// <summary>

    /// 時間類型 均為3

    /// </summary>

    public int Event_Type

        get { return _event_Type; }

        set { _event_Type = value; }

    string _eventCategory;

    /// 日志分類描述,自定義

    public string EventCategory

        get { return _eventCategory; }

        set { _eventCategory = value; }

    int _event_ID;

    /// 日志分類号

    public int Event_ID

        get { return _event_ID; }

        set { _event_ID = value; }

    string _computerName;

    /// 計算機IP

    public string ComputerName

        get { return _computerName; }

        set { _computerName = value; }

    string _mac_Address;

    /// 計算機Mac位址

    public string Mac_Address

        get { return _mac_Address; }

        set { _mac_Address = value; }

    string _userName;

    /// 系統登陸使用者

    public string UserName

        get { return _userName; }

        set { _userName = value; }

    string _sourceType;

    /// Rier

    public string SourceType

        get { return _sourceType; }

        set { _sourceType = value; }

    string _source;

    /// Rier Recorder audit

    public string Source

        get { return _source; }

        set { _source = value; }

    string _description;

    /// 日志描述資訊

    public string Description

        get { return _description; }

        set { _description = value; }

}

第二個類  MyLayout.cs 把我們定義的屬性轉換為log4net所能識别的屬性

using System.Collections.Generic;

using System.Text;

using log4net.Layout.Pattern;

using log4net.Layout;

using log4net.Core;

using System.Reflection;

namespace LogComponent

    class MyLayout:PatternLayout

        public MyLayout()

        {

            this.AddConverter("property", typeof(MyMessagePatternConverter));

        }

第三個類

    class MyMessagePatternConverter:PatternLayoutConverter

        protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)

            if (Option != null)

            {

                // Write the value for the specified key

                WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));

            }

            else

                // Write all the key value pairs

                WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());

            //if (Option != null)

            //{

            //    // Write the value for the specified key

            //    WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty(Option));

            //}

            //else

            //    // Write all the key value pairs

            //    WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());

        /// <summary>

        /// 通過反射擷取傳入的日志對象的某個屬性的值

        /// </summary>

        /// <param name="property"></param>

        /// <returns></returns>

        private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)

            object propertyValue = string.Empty;

            PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);

            if (propertyInfo != null)

                propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);

            return propertyValue;

代碼頁

記得在該項目中添加log4net引用

using System.Collections;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using LogComponent;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

public partial class Test : System.Web.UI.Page

    protected void Page_Load(object sender, EventArgs e)

    protected void Button1_Click(object sender, EventArgs e)

        log4net.ILog log = log4net.LogManager.GetLogger("myLogger");

        log.Info(new LogContent(3,"登陸系統",1,"127.0.0.1","111111","mhy","11111","11111111","登陸成功"));