log4net日誌記錄

weixin_34127717發表於2018-07-09

1、1.在assemblyInfo.cs新增

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

2、2.在根目錄新增log4net.config檔案,內容如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
  </configSections>
  <log4net>
    <logger name="log" additivity="false">
      <level value="ALL"/>
      <appender-ref ref="SysAppender" />
    </logger>
   
    <!--Oracle資料庫-->
    <appender name="OracleAppender" type="log4net.Appender.AdoNetAppender">
      <!-- Oracle資料來源-->
      <connectionType value="Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
      <!-- Oracle連線字串-->
      <connectionString value="DATA SOURCE=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.3.206)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=orcl)));PASSWORD=watdb;PERSIST SECURITY INFO=True;USER ID=watdb;"/>

      <commandText value="INSERT INTO SYS_LOG(Dates,Levels,Logger,Message,Exception,ClientUser,ClientIP,RequestUrl,Action)VALUES(:Dates,:Levels,:Logger,:Message,:Exception,:ClientUser,:ClientIP,:RequestUrl,:Action)"/>
      <!--  
             設定快取區大小  
             1表明有一條日誌就要寫入  
             如果10就表示日誌到達10條時一起寫入  
             -->
      <bufferSize value="0"/>
      <parameter>
        <parameterName value=":Dates" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout"/>
      </parameter>
      <parameter>
        <parameterName value=":Levels" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value=":Logger" />
        <dbType value="String" />
        <size value="200" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value=":Message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value=":Exception" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%exception" />
        </layout>
      </parameter>
      <!--DIY-->
      <parameter>
        <parameterName value=":ClientUser" />
        <dbType value="String" />
        <size value="100" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{ClientUser}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value=":ClientIP" />
        <dbType value="String" />
        <size value="20" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{ClientIP}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value=":RequestUrl" />
        <dbType value="String" />
        <size value="500" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{RequestUrl}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value=":Action" />
        <dbType value="String" />
        <size value="20" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{Action}" />
        </layout>
      </parameter>
    </appender>
    <!--Sqlite資料庫-->
    <appender name="SqliteAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="0" />
      <connectionType value="System.Data.SQLite.SQLiteConnection, System.Data.SQLite, Version=1.0.98.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
      <connectionString value="Data Source=|DataDirectory|test.db;Version=3;" />
      <commandText value="INSERT INTO Log (Date, Level, Logger, ClientUser,ClientIP, RequestUrl,Action, Message, Exception) VALUES (@Date, @Level, @Logger,@ClientUser,@ClientIP, @RequestUrl,@Action, @Message, @Exception)" />
      <parameter>
        <parameterName value="@Date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </parameter>
      <parameter>
        <parameterName value="@Level" />
        <dbType value="String" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Logger" />
        <dbType value="String" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@ClientUser" />
        <dbType value="String" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{ClientUser}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@ClientIP" />
        <dbType value="String" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{ClientIP}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@RequestUrl" />
        <dbType value="String" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{RequestUrl}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Action" />
        <dbType value="String" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{Action}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Message" />
        <dbType value="String" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Exception" />
        <dbType value="String" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%exception" />
        </layout>
      </parameter>
    </appender>
    <!--SqlServer資料庫-->
    <appender name="SqlServerAppender" type="log4net.Appender.AdoNetAppender">
      <!-- SqlServer資料來源-->
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <!-- SqlServer連線字串-->
      <connectionString value="data source=.;initial catalog=wkmvc_db;integrated security=false;persist security info=True;User ID=sa_wkmvc;Password=123456" />
      <connectionString value="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\wkmvc_db.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework" />
      <commandText value="INSERT INTO SYS_LOG(Dates,Levels,Logger,ClientUser,ClientIP,RequestUrl,Action,Message,Exception)VALUES(@Dates,@Levels,@Logger,@ClientUser,@ClientIP,@RequestUrl,@Action,@Message,@Exception)"/>
      <!--  
             設定快取區大小  
             1表明有一條日誌就要寫入  
             如果10就表示日誌到達10條時一起寫入  
             -->
      <bufferSize value="0"/>
      <parameter>
        <parameterName value="@Dates" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </parameter>
      <parameter>
        <parameterName value="@Levels" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Logger" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Exception" />
        <dbType value="String" />
        <size value="2000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
      <!--DIY-->
      <parameter>
        <parameterName value="@ClientUser" />
        <dbType value="String" />
        <size value="100" />
        <layout type="log4net.Layout.PatternLayout" >
          <param name="ConversionPattern" value="%property{ClientUser}"/>
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@ClientIP" />
        <dbType value="String" />
        <size value="100" />
        <layout type="log4net.Layout.PatternLayout" >
          <param name="ConversionPattern" value="%property{ClientIP}"/>
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@RequestUrl" />
        <dbType value="String" />
        <size value="500" />
        <layout type="log4net.Layout.PatternLayout" >
          <param name="ConversionPattern" value="%property{RequestUrl}"/>
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Action" />
        <dbType value="String" />
        <size value="100" />
        <layout type="log4net.Layout.PatternLayout" >
          <param name="ConversionPattern" value="%property{Action}"/>
        </layout>
      </parameter>
    </appender>
    <!--記錄到檔案-->
    <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <param name="File" value="datalog" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="\\yyyy-MM-dd&quot;.log&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d - %m%n" />
        <param name="Header" value="&#xD;&#xA;----------------------begin--------------------------&#xD;&#xA;" />
        <param name="Footer" value="&#xD;&#xA;----------------------end--------------------------&#xD;&#xA;" />
      </layout>
    </appender>
  </log4net>
</configuration>
<!--
   呼叫例項
   log4net.ILog log = log4net.LogManager.GetLogger("Filelog");
   log.Info(Message);
   
    %m(message):輸出的日誌訊息,如ILog.Debug(…)輸出的一條訊息

    %n(new line):換行

    %d(datetime):輸出當前語句執行的時刻

    %r(run time):輸出程式從執行到執行到當前語句時消耗的毫秒數

    %t(thread id):當前語句所在的執行緒ID

    %p(priority): 日誌的當前優先順序別,即DEBUG、INFO、WARN…等

    %c(class):當前日誌物件的名稱
    
    %L:輸出語句所在的行號

    %F:輸出語句所在的檔名

    %-數字:表示該項的最小長度,如果不夠,則用空格填充

    例如,轉換模式為%r [%t]%-5p %c - %m%n 的 PatternLayout 將生成類似於以下內容的輸出:

    176 [main] INFO  org.foo.Bar - Located nearest gas station.
    -->

3、可定義個日誌幫助類,如下:

public static class LogHelper
    {
        static ILog log = LogManager.GetLogger("log");

        public static void Save(string content,Exception ex)
        {
            log.Error(content, ex);
        }
        public static void Save(string content)
        {
            log.Error(content);
        }
        public static void SaveAsyn(string content)
        {
            Task.Run( ()=> log.Error(content));
        }
        public static void SaveAsyn(string content,Exception ex)
        {
            Task.Run(() => log.Error(content, ex));
        }
    }

3 按日期及檔案大小記錄

    <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <param name="File" value="datalog" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Composite" />
      <param name="DatePattern" value="\\yyyy-MM-dd&quot;.log&quot;" />
      <param name="StaticLogFileName" value="false" />
      <param name="MaximumFileSize" value="1MB" />
      <param name="MaxSizeRollBackups" value="-1" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d - %m%n" />
        <param name="Header" value="&#xD;&#xA;----------------------begin--------------------------&#xD;&#xA;" />
        <param name="Footer" value="&#xD;&#xA;----------------------end--------------------------&#xD;&#xA;" />
      </layout>
    </appender>

相關文章