Serilog 導入紀錄 for ASP.NET Core

試著導入Serilog並與NLog比較。結論:淺的部份差不多;深的部份未用過。

Why Serilog?

為何要導入Serilog / NLog這類工具模組?也有預設Logger啊?原因有點無言,預設的 logger provider 無法寫入檔案,而實務上我們希望log可以寫入檔案。

ASP.NET Core 包括下列記錄提供者

  • 主控台

  • 偵錯

  • EventSource

  • EventLog

  • AzureAppServicesFile 和 AzureAppServicesBlob

  • ApplicationInsights

也許或許未來預設的Logger也可以寫入檔案,然而現在就是沒有。

NLog vs log4net vs Serilog

  1. log4net 於2001年開啟。

  2. NLog於2006發佈。

  3. Serilog於2013年發佈。宣稱可產製結構化的log,俱體上就是JSON格式的紀錄檔。

這三套目的一樣,主要規格也近乎相同,導入程序也差不多簡單,可以當作是每隔數年的重構版,所以選用最新版的Serilog就對了。其中Enrich應該是Serilog的賣點,但本人無力深入研究~~~

導入案例紀錄

我的專案類型

ASP.NET Core / Blazor Server App on .NET 5

NuGet安裝Serilog模組

  1. Serilog.AspNetCoreMain package

  2. Serilog.Settings.Configuration — Microsoft.Extensions.Configuration (appsettings.json) support for Serilog

  3. Serilog.Sinks.Console — A Serilog sink that writes log events to the console/terminal.

  4. Serilog.Sinks.File — Write Serilog events to text files in plain or JSON format.

  5. Serilog.Sinks.Async — Asynchronous sink wrapper for Serilog

  6. Serilog.Formatting.Compact — A simple, compact JSON-based event format for Serilog. (賣點在此)

  7. Serilog.Sinks.PeriodicBatching — A wrapper for Serilog sinks that asynchronously emits events in batches, useful when logging to a slow and/or remote target. (可用來客製化寫入標的)

Serilog組態設定紀錄:appsettings.json

Serilog的組態有二種方式,一是透過appsettings.json (建議)。二是寫在啟動程式碼區段(不建議)。

appsettings.json
{
  //"Logging": {
  //  "LogLevel": {
  //    "Default": "Information",
  //    "Microsoft": "Warning",
  //    "Microsoft.Hosting.Lifetime": "Information",
  //    "Microsoft.AspNetCore.SignalR": "Debug",
  //    "Microsoft.AspNetCore.Http.Connections": "Debug"
  //  }
  //},
  "Serilog": {
    "Using": [ "SeriLog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Async" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft.AspNetCore.SignalR": "Debug",
        "Microsoft.AspNetCore.Http.Connections": "Debug",
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "Async",
        "Args": {
          "configure": [
            {
              "Name": "File",
              "Args": {
                "path": "Log/log.txt",
                "rollingInterval": "Day",
                "restrictedToMinimumLevel": "Error"
              }
            },
            {
              // Seriolog的賣點在此
              "Name": "File",
              "Args": {
                "path": "Log/myapp.json",
                "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
                "rollingInterval": "Day"
              }
            }
          ]
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], // 尚不知此段設定的用途為何?
    "Properties": {
      "Application": "SerilogExample" // 尚不知此設定的出現條件?
    }
  },
  "AllowedHosts": "*"
}

Serilog啟動程式碼:Program.cs

Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using System.IO;

namespace BlazorServerApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(Configuration)
                .CreateLogger();

            try
            {
                Log.Information("Web host start.");
                CreateHostBuilder(args).Build().Run();
                Log.Information("Web host exit.");
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Web host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog() 
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

        /// <summary>
        /// used by Serilog to read appsettings.json
        /// </summary>
        public static IConfiguration Configuration => new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
            .AddJsonFile($"appsettings.{Environment.MachineName}.json", optional: true)
            .AddEnvironmentVariables()
            .Build();
    }
}

開始使用ILogger

請膜拜google大神。

參考文章

Serilog office site
Compact JSON event format (賣點在此)
List of available Serilog sinks
Serilog導入主要參考文章

Last updated