1. 程式人生 > >AspNetCore 使用log4net+IExceptionFilter 記錄錯誤日誌

AspNetCore 使用log4net+IExceptionFilter 記錄錯誤日誌

錯誤日誌的好處我就不說了,大家都心裡有數,那今天浩子就給大家說一說基本的錯誤日誌吧這次通過log4net記錄日誌。

原來寫過一個關於Nlog的日誌框架,傳送門為:https://www.cnblogs.com/ZaraNet/p/9957655.html 

使用呢,直接nuget log4net吧,這個就不多說了,那我們看一下如何使用。

1.建立log4net.config

2.配置Startup.

3.定義HttpGlobalExceptionFilter

在根目錄建立log4net.config,其定義如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <log4net>
        <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
            <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
    </appender>
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
            <file value="Log/" />
            <appendToFile value="true" />
            <rollingStyle value="Composite" />
            <staticLogFileName value="false" />
            <datePattern value="yyyyMMdd'.log'" />
            <maxSizeRollBackups value="10" />
            <maximumFileSize value="1MB" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
        <root>
            <level value="ALL" />
            <appender-ref ref="ConsoleAppender" />
            <appender-ref ref="FileAppender" />
            <appender-ref ref="RollingLogFileAppender" />
    </root>
  </log4net>
</configuration>

 在Startup.cs定義如下,記得引用相應的名稱空間。

public static ILoggerRepository repository { get; set; }

public Startup(IConfiguration configuration)
{
    Configuration = configuration;

    //載入log4net日誌配置檔案
    repository = LogManager.CreateRepository("NETCoreRepository");
    XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

    services.AddMvc(options =>
    {
        options.Filters.Add<Models.HttpGlobalExceptionFilter>(); //加入全域性異常類
    });
}