C# 利用log4net 把日誌寫入到數據庫

效果圖:html

1:第一步建立SQL表結構
  1.  
    CREATE TABLE [dbo].[LogDetails] (
  2.  
    [LogID] int NOT NULL IDENTITY( 1, 1) ,
  3.  
    [LogDate] datetime NOT NULL ,
  4.  
    [LogThread] nvarchar( 100) NOT NULL ,
  5.  
    [LogLevel] nvarchar( 200) NOT NULL ,
  6.  
    [LogLogger] nvarchar( 500) NOT NULL ,
  7.  
    [LogMessage] nvarchar( 3000) NOT NULL ,
  8.  
    [LogActionClick] nvarchar( 4000) NULL ,
  9.  
    [UserName] nvarchar( 30) NULL ,
  10.  
    [UserIP] varchar( 20) NULL
  11.  
    )

2:建立項目而後下載log4net.dll 在項目中添加引用 http://logging.apache.org/log4net/download_log4net.cgi下載Binaries 下面的web

3:建立 log4net.config數據庫

 

  1.  
    <?xml version="1.0" encoding="utf-8" ?>
  2.  
     
  3.  
    <log4net debug="false">
  4.  
    <!-- name屬性指定其名稱,type則是log4net.Appender命名空間的一個類的名稱,意思是,指定使用哪一種介質-->
  5.  
    <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
  6.  
    <!--日誌緩存寫入條數 設置爲0時只要有一條就馬上寫到數據庫-->
  7.  
    <bufferSize value="0" />
  8.  
    <!--日誌數據庫鏈接串-->
  9.  
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  10.  
    <connectionString value="DATABASE=GoodLook;SERVER=xx.xx.140.170;UID=sa;PWD=123456a;Connect Timeout=30;" />
  11.  
    <!--日誌數據庫腳本-->
  12.  
    <commandText value="INSERT INTO LogDetails ([LogDate],[LogThread],[LogLevel],[LogLogger],[LogActionClick],[LogMessage],[UserName],[UserIP]) VALUES (@log_date, @thread, @log_level, @logger, @ActionsClick, @message,@UserName,@UserIP)" />
  13.  
    <!--日誌時間LogDate -->
  14.  
    <parameter>
  15.  
    <parameterName value="@log_date" />
  16.  
    <dbType value="DateTime" />
  17.  
    <layout type="log4net.Layout.RawTimeStampLayout" />
  18.  
    </parameter>
  19.  
    <!--線程號-->
  20.  
    <parameter>
  21.  
    <parameterName value="@thread" />
  22.  
    <dbType value="String" />
  23.  
    <size value="100" />
  24.  
    <layout type="log4net.Layout.PatternLayout">
  25.  
    <conversionPattern value="%t" />
  26.  
    </layout>
  27.  
    </parameter>
  28.  
    <!--日誌類型LogLevel -->
  29.  
    <parameter>
  30.  
    <parameterName value="@log_level" />
  31.  
    <dbType value="String" />
  32.  
    <size value="200" />
  33.  
    <layout type="log4net.Layout.PatternLayout">
  34.  
    <conversionPattern value="%p" />
  35.  
    </layout>
  36.  
    </parameter>
  37.  
    <!--日誌名稱-->
  38.  
    <parameter>
  39.  
    <parameterName value="@logger" />
  40.  
    <dbType value="String" />
  41.  
    <size value="500" />
  42.  
    <layout type="log4net.Layout.PatternLayout">
  43.  
    <conversionPattern value="%logger" />
  44.  
    </layout>
  45.  
    </parameter>
  46.  
    <parameter>
  47.  
    <parameterName value="@message" />
  48.  
    <dbType value="String" />
  49.  
    <size value="3000" />
  50.  
    <layout type="Log4NetApply.MyLayout">
  51.  
    <conversionPattern value="%property{Message}" />
  52.  
    </layout>
  53.  
    </parameter>
  54.  
    <parameter>
  55.  
    <parameterName value="@ActionsClick" />
  56.  
    <dbType value="String" />
  57.  
    <size value="4000" />
  58.  
    <layout type="Log4NetApply.MyLayout" >
  59.  
    <conversionPattern value = "%property{ActionsClick}"/>
  60.  
    </layout>
  61.  
    </parameter>
  62.  
    <!--自定義UserName -->
  63.  
    <parameter>
  64.  
    <parameterName value="@UserName" />
  65.  
    <dbType value="String" />
  66.  
    <size value="30" />
  67.  
    <layout type="Log4NetApply.MyLayout" >
  68.  
    <!--log4net.MDC.Set("UserName", "asdfasdf");
  69.  
    <conversionPattern value = "%X{UserName}"/>-->
  70.  
    <conversionPattern value = "%property{UserName}"/>
  71.  
    </layout>
  72.  
    </parameter>
  73.  
    <parameter>
  74.  
    <parameterName value="@UserIP" />
  75.  
    <dbType value="String" />
  76.  
    <size value="20" />
  77.  
    <layout type="Log4NetApply.MyLayout" >
  78.  
    <conversionPattern value = "%property{UserIP}"/>
  79.  
    </layout>
  80.  
    </parameter>
  81.  
    </appender>
  82.  
    <!-- setup the root category, add the appenders and set the default level -->
  83.  
    <root>
  84.  
    <level value="Warn"/> <!-- 定義記錄的日誌級別-->
  85.  
    <level value="Info"/>
  86.  
    <level value="Debug"/>
  87.  
    <level value="Fine"/>
  88.  
    <appender-ref ref="ADONetAppender" /> <!-- 記錄到什麼介質中-->
  89.  
    </root>
  90.  
    <!-- specify the level for some specific categories -->
  91.  
    <!--//關於上邊root到logger這塊,若是同時出現,有可能會出現重複插入記錄的狀況:-->
  92.  
    <!--<logger name="iNotes">
  93.  
    <level value="WARN"/>
  94.  
    <level value="INFO"/>
  95.  
    <level value="DEBUG"/>
  96.  
    <level value="FINE"/>
  97.  
    <appender-ref ref="ADONetAppender"/>
  98.  
    </logger>
  99.  
    <logger name="StellaLogger">
  100.  
    <level value="ALL"/>
  101.  
    <appender-ref ref="AdoNetAppender" />
  102.  
    </logger>-->
  103.  
    <appender name="ReflectionLayout" type="log4net.Appender.RollingFileAppender,log4net">
  104.  
     
  105.  
    <!--日誌文件路徑,按文件大小方式輸出時在這裏指定文件名,而且前面的日誌按天在文件名後自動添加當天日期造成文件-->
  106.  
    <param name="File" value="D:/Log/" />
  107.  
     
  108.  
    <!--是否追加到文件-->
  109.  
    <param name="AppendToFile" value="true" />
  110.  
     
  111.  
    <!--記錄日誌寫入文件時,不鎖定文本文件-->
  112.  
    <!--<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />-->
  113.  
     
  114.  
    <!--Unicode編碼-->
  115.  
    <!--<Encoding value="UTF-8" />-->
  116.  
     
  117.  
    <!--最多產生的日誌文件數,value="-1"爲不限文件數-->
  118.  
    <!--<param name="MaxSizeRollBackups" value="10" />-->
  119.  
     
  120.  
    <!--是否只寫到一個文件中-->
  121.  
    <param name="StaticLogFileName" value="false" />
  122.  
     
  123.  
    <!--按照何種方式產生多個日誌文件(日期[Date],文件大小[Size],混合[Composite])-->
  124.  
    <param name="RollingStyle" value="Composite" />
  125.  
     
  126.  
    <!--按日期產生文件夾,文件名[在日期方式與混合方式下使用]-->
  127.  
    <param name="DatePattern" value="yyyy-MM-dd/"ReflectionLayout.log"" />
  128.  
    <!--<param name="DatePattern" value="yyyyMMdd/yyyyMMdd"-TimerServer.log"" />-->
  129.  
    <!--<param name="DatePattern" value="yyyyMMdd/"TimerServer/TimerServer.log"" />-->
  130.  
     
  131.  
    <!--每一個文件的大小。只在混合方式與文件大小方式下使用,超出大小的在文件名後自動增長1從新命名-->
  132.  
    <param name="maximumFileSize" value="500KB" />
  133.  
     
  134.  
    <!--記錄的格式。-->
  135.  
    <layout type="TGLog.ExpandLayout2.ReflectionLayout,TGLog">
  136.  
    <param name="ConversionPattern" value="記錄時間:%date 線程ID:[%thread] 日誌級別:%-5level 記錄類:%logger 操做者ID:%property{Operator} 操做類型:%property{Action}%n 當前機器名:%property%n當前機器名及登陸用戶:%username %n 記錄位置:%location%n 消息描述:%property{Message}%n 異常:%exception%n 消息:%message%newline%n%n" />
  137.  
    </layout>
  138.  
    </appender>
  139.  
     
  140.  
     
  141.  
     
  142.  
     
  143.  
    </log4net>

 

4:在Web.config 裏面加 configSections 節點 (CS可直接寫在app.config裏面,或者都寫在一個config裏面)apache

 

  1.  
    <configuration>
  2.  
    <strong> <span style="color:#FF0000;"> <configSections>
  3.  
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  4.  
    </configSections>
  5.  
    <log4net configSource="log4net.config"/> </span> </strong>
  6.  
     
  7.  
    <system.web>
  8.  
    <compilation debug="true" targetFramework="4.5" />
  9.  
    <httpRuntime targetFramework="4.5" />
  10.  
    </system.web>
  11.  
     
  12.  
    </configuration>

5:Properties 屬性下面的AssemblyInfo.cs 追加 必須有這個,不然寫入不到數據庫中

 

 

  1.  
    //[assembly: log4net.Config.XmlConfigurator(Watch = true)]
  2.  
    //注意: ConfigFile 能夠指定相對路徑 和 絕對路徑。 eg: /log/xxxx.log 或者 d://log//xxxx.log
  3.  
    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]

6:添加 Global.asax

 

而後在Application_Start 追加 讀取配置程序文件緩存

 

  1.  
    protected void Application_Start(object sender, EventArgs e)
  2.  
    {
  3.  
    //應用程序啓動時,自動加載配置log4Net
  4.  
    XmlConfigurator.Configure();
  5.  
    }
7:建立自定義類 LogPublicClass.cs,爲了方便寫入數據庫中 自定義的一些信息

 

 

  1.  
    using log4net.Layout;
  2.  
    using log4net.Layout.Pattern;
  3.  
    using System;
  4.  
    using System.Collections.Generic;
  5.  
    using System.Linq;
  6.  
    using System.Reflection;
  7.  
    using System.Web;
  8.  
     
  9.  
    namespace Log4NetApply
  10.  
    {
  11.  
    /// <summary>
  12.  
    /// 包含了全部的自定字段屬性
  13.  
    /// </summary>
  14.  
    public class LogContent
  15.  
    {
  16.  
    public LogContent(string macAddress, string computerName, string actionsclick, string description)
  17.  
    {
  18.  
    UserIP = macAddress;
  19.  
    UserName = computerName;
  20.  
    ActionsClick = actionsclick;
  21.  
    Message = description;
  22.  
    }
  23.  
     
  24.  
    /// <summary>
  25.  
    /// 訪問IP
  26.  
    /// </summary>
  27.  
    public string UserIP { get; set; }
  28.  
     
  29.  
    /// <summary>
  30.  
    /// 系統登錄用戶
  31.  
    /// </summary>
  32.  
    public string UserName { get; set; }
  33.  
     
  34.  
    /// <summary>
  35.  
    /// 動做事件
  36.  
    /// </summary>
  37.  
    public string ActionsClick { get; set; }
  38.  
     
  39.  
    /// <summary>
  40.  
    /// 日誌描述信息
  41.  
    /// </summary>
  42.  
    public string Message { get; set; }
  43.  
     
  44.  
     
  45.  
    }
  46.  
    public class MyLayout : PatternLayout
  47.  
    {
  48.  
    public MyLayout()
  49.  
    {
  50.  
    this.AddConverter( "property", typeof(LogInfoPatternConverter));
  51.  
    }
  52.  
    }
  53.  
     
  54.  
    public class LogInfoPatternConverter : PatternLayoutConverter
  55.  
    {
  56.  
     
  57.  
    protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
  58.  
    {
  59.  
    if (Option != null)
  60.  
    {
  61.  
    // Write the value for the specified key
  62.  
    WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
  63.  
    }
  64.  
    else
  65.  
    {
  66.  
    // Write all the key value pairs
  67.  
    WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
  68.  
    }
  69.  
    }
  70.  
    /// <summary>
  71.  
    /// 經過反射獲取傳入的日誌對象的某個屬性的值
  72.  
    /// </summary>
  73.  
    /// <param name="property"></param>
  74.  
    /// <returns></returns>
  75.  
     
  76.  
    private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)
  77.  
    {
  78.  
    object propertyValue = string.Empty;
  79.  
    PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);
  80.  
    if (propertyInfo != null)
  81.  
    propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
  82.  
    return propertyValue;
  83.  
    }
  84.  
    }
  85.  
    }

8:示例使用

 

 

  1.  
    try
  2.  
    {
  3.  
    log.Info( new LogContent( "127.0.0.1", "111111", "登錄系統", "登錄成功"));
  4.  
    var ss = 1 - int.Parse( "sss");
  5.  
    }
  6.  
    catch(Exception ex)
  7.  
    {
  8.  
    log.Error( new LogContent( "127.0.0.1", "111111", "登錄系統", ex.Message+ ":"+ex.StackTrace));
  9.  
    }

其餘自行參考下列文章

 

 

  1.  
    http://www.cnblogs.com/kissazi2/p/3393151.html
  2.  
    http://blog.csdn.net/zdw_wym/article/details/48802821
  3.  
    http://blog.csdn.net/ydm19891101/article/details/50561638
  4.  
    http://www。w2bc。com/Article/70140
  5.  
    http://www.cnblogs.com/yuangang/archive/2016/05/16/5497140.html

 

 

出處:https://blog.csdn.net/kongwei521/article/details/52242319app

相關文章
相關標籤/搜索