關於Serilog

  • 44
  • 0
  • 2024-06-03

asp.net core log

為什麼需要log機制?

  1. 可以精準找到錯誤狀況
  2. 詳細資訊可以提供診斷問題
  3. 可以明確說出錯誤原因(保障自己)

Serilog是一個結構化記錄框架,用途可以放在檔案和資料庫,這幾年算是非常成熟的框架。

如何安裝?

dotnet add package Serilog.AspNetCore

Install-Package Serilog.AspNetCore

或是到Nuget當中尋找Serilog.AspNetCore

log level

.NET Core 原生: Trace = 0, Debug = 1, Information = 2, Warning = 3, Error = 4, Critical = 5, None = 6 

Serilog: Verbose = 0, Debug = 1, Information = 2, Warning = 3, Error = 4, Fatal = 5

在program.cs設定

// 設置
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
    .Enrich.FromLogContext()
    .WriteTo.Console()      //印出螢幕
    .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();
// 使用 Serilog
builder.Host.UseSerilog();

關於LogEventLevel.Warning

只會寫入Warning等級以上(包含),才會做記錄。

如果要加入記錄參數。

app.UseSerilogRequestLogging();

讀取設定檔案

// 設置: 讀取組態檔 (appsettings.json)
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .CreateLogger();

appseting.json

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft.AspNetCore": "Warning"
      }
    },
    "Enrich": [ "FromLogContext" ],
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
            "path":  "./logs/log-.json",
            "rollingInterval": "Day",
            "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
          }
      }
    ]
  },
  "AllowedHosts": "*"
}

使用Seq

用docker快速架起seq伺服器

docker run --name seq -d --restart unless-stopped -e ACCEPT_EULA=Y -p 5341:80 datalust/seq:latest

改寫如下

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .WriteTo.Seq("http://localhost:5341")
    .CreateLogger();

builder.Host.UseSerilog((hostingContext, loggerConfiguration) =>
{
    loggerConfiguration
        .Enrich.FromLogContext()
        .WriteTo.Console()
        .WriteTo.Debug()
        //添加Seq
        .WriteTo.Seq("http://localhost:5341");
});

 

更詳細補充如底下參考來源

參考來源:

https://www.jasperstudy.com/2024/03/aspnet-core-8-mvc-serilog.html

https://github.com/nethawkChen/dotnet8-Serilog

https://ithelp.ithome.com.tw/articles/10300929

老E隨手寫