SeriLog 設定之眉角

Installation

  1. 用 NuGet 搜尋 Serilog.AspNetCore安裝套件 image

  2. Program.cs 加入設定 image

    1
    2
    3
    4
    5
    6
    7
    
    Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
            .MinimumLevel.Override("System", LogEventLevel.Warning)//使用MinimumLevel 來設定 LogLevel 層級,如果來源為 Microsoft 及 系統的訊息 則LogLevel 層級為 警告
            .WriteTo.Console(new RenderedCompactJsonFormatter())
            .WriteTo.File(new CompactJsonFormatter().ToString())//Output templates, 輸出至Console及檔案
            .Enrich.FromLogContext()
            .CreateLogger();

    CompactJsonFormatter 將保留消息模板、屬性和格式信息,以便稍後可以創建呈現的消息。當 JSON 旨在在沒有消息模板呈現的環境中使用時,可以改用 RenderedCompactJsonFormatter

    image loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration) : 讀取現在的Configuration

  3. appsetting.json 加入設定 image

    • Microsoft.Hosting.Lifetime : 應用程式生命週期事件的通知
    • Microsoft.EntityFrameworkCore.Database.Command : 紀錄 EF Core 自動產生的 SQL 命令
  4. Startup.cs 設定 image

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    
    app.UseSerilogRequestLogging(options =>
             {
                 // Customize the message template
                 options.MessageTemplate = "Handled {RequestPath}";
    
                 // Emit debug-level events instead of the defaults
                 options.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Debug;
    
                 // Attach additional properties to the request completion event
                 options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
                 {
                     diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
                     diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
                 };
             });

Usage

  1. 在需要的地方加入 log

    1. 先 using Microsoft.Extensions.Logging
    2. 加入建構式 image
    3. 在需要 log 的部分加入 log 記錄 image

      可以自訂訊息等級 image

  2. 因在Program.csappsetting.json有加入設定,其餘 System 的操作及 Database 的讀取皆會被 log 下來 image

    image

參考資料

  1. Github - serilog-aspnetcore
  2. Github - Serilog.Formatting.Compact
  3. Microsoft - .NET Core 與 ASP.NET Core 中的記錄
  4. WilL Blog - ASP.NET Core 如何紀錄 Entity Framework Core 5.0 自動產生的 SQL 命令
  5. m@rcus 學習筆記 - [NETCore] 結構化日誌 Serilog - 配置設定
  6. C# Corner - How To Implement Logging Using Serilog In ASP.NET Core 5.0 Application With Database
0%