1. 程式人生 > >Log4Net基礎配置

Log4Net基礎配置

publickey app 嚴重 target 創建 strong mar ssa style

一.組件引用

1.首先nuget中引入log4net

2.項目AssemblyInfo.cs引入log4net, 文件路徑:項目/Properties/AssemblyInfo.cs

:如果不在此引入直接在global中引入,在不部署到IIS中時本地測試是可以用的,如果要部署到IIS中則需要添加,請註意。

技術分享圖片

3.global中引入

log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));

二.log4net.config配置

1.寫入文件

註意:如果是有多個appender寫文件配置,如果記錄則會同時寫入多個appender指定的文件中,如需解決此問題,需要看底層代碼重寫,目前暫時用不到所以沒去處理。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>

  <log4net>
    <!--定義輸出到文件中-->
    <appender name="
RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--輸出文件路徑--> <file type="log4net.Util.PatternString" value="Log/%date{yyyy}/%date{yyyyMM}/"/> <appendToFile value="true"/> <rollingStyle value="Date"/> <datePattern value="yyyyMMdd‘.txt‘
"/> <staticLogFileName value="false"/> <param name="MaxSizeRollBackups" value="100"/> <layout type="log4net.Layout.PatternLayout"> <!--每條日誌末尾的文字說明--> <!--輸出格式--> <conversionPattern value="%newline %n記錄時間:%date %n線程ID:[%thread] %n日誌級別: %-5level %n類:%logger property: [%property{NDC}] - %n描述:%message%newline %n"/> </layout> </appender> <root> <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --> <level value="ALL"/> <!--文件形式記錄日誌--> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> </configuration>

2.寫入數據庫

註意點:

  1. 寫入數據庫appender type類型為:log4net.Appender.AdoNetAppender
  2. 可以為多種級別信息創建不同的appender,以name區分
  3. 請註意每添加一個appender,需要增加過濾器用於識別logger,同時需要增加DenyAllFilter,防止其他appender也插入日誌,loggerToMatch中value對應代碼中 logger別名。
 <filter type="log4net.Filter.LoggerMatchFilter">
        <loggerToMatch value="gops" />
  </filter>
 <filter type="log4net.Filter.DenyAllFilter" />

LogHelper類:

 /// <summary>
    /// 日誌輔助類
    /// </summary>
   public class LogHelper
    {
       private static log4net.ILog log = null;
       static LogHelper()
       {
           log = log4net.LogManager.GetLogger("gops");
       }

       /// <summary>
       /// 普通日誌
       /// </summary>
       /// <param name="content"></param>
       public static void Info(string content)
       {
           try
           {
               log.Info(content);
           }
           catch { }
       }

       /// <summary>
       /// 調試日誌
       /// </summary>
       /// <param name="content"></param>
       public static void Debug(string content, Exception ex = null)
       {
           try
           {
               log.Debug(content,ex);
           }
           catch { }
       }

       /// <summary>
       /// 錯誤日誌
       /// </summary>
       /// <param name="content"></param>
       public static void Error(string content,Exception ex=null)
       {
           try
           {
               log.Error(content,ex);
           }
           catch { }
       }

       /// <summary>
       /// 嚴重錯誤日誌
       /// </summary>
       /// <param name="content"></param>
       public static void Fatal(string content, Exception ex = null)
       {
           try
           {
               log.Fatal(content,ex);
           }
           catch { }
       }

       /// <summary>
       /// 警告日誌
       /// </summary>
       /// <param name="content"></param>
       public static void Warn(string content, Exception ex = null)
       {
           try
           {
               log.Warn(content,ex);
           }
           catch { }
       }
    }

完整代碼:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>

  <log4net>
    <!--<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />
      <connectionType value="System.Data.SqlClient.SqlConnection,System.Data, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089" />
      <connectionString value="數據庫連接" />
      <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) 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="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%thread" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <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>
      <filter type="log4net.Filter.LoggerMatchFilter">
        <loggerToMatch value="gops1" />
      </filter>
      <filter type="log4net.Filter.DenyAllFilter" />
    </appender>-->

    <!--接口日誌-->
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />
      <connectionType value="System.Data.SqlClient.SqlConnection,System.Data, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089" />
      <connectionString value="數據庫連接" />
      <commandText value="execute LogInsert @tablename,@thread,@log_level,@logger,@message,@exception" />
      <parameter>
        <parameterName value="@tablename" />
        <dbType value="String" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date{OpenApiyyyyMM}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </parameter>
      <parameter>
        <parameterName value="@thread" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%thread" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <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>
      <!--請註意每添加一個appender,需要增加過濾器用於識別logger,同時需要增加DenyAllFilter,防止其他appender也插入日誌-->
      <!--<filter type="log4net.Filter.LoggerMatchFilter">
        <loggerToMatch value="OpenApiLog" />
      </filter>
      <filter type="log4net.Filter.DenyAllFilter" />-->
      <filter type="log4net.Filter.LoggerMatchFilter">
        <loggerToMatch value="gops" />
      </filter>
      <filter type="log4net.Filter.DenyAllFilter" />
    </appender>
    <root>
      <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->
      <level value="all" />
      <appender-ref ref="AdoNetAppender"/>
      <!--<appender-ref ref="OpenApiAppender"/>-->
    </root>
  </log4net>
</configuration>

Log4Net基礎配置