ASP.NET Core Logging With Serilog

2024-05-29

筆記如何使用 Serilog 在 ASP.NET Core 當中將 Log 儲存至 SQL Server。

logo

說明

一、Nuget 安裝以下 Packages

Project.csproj

<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.MSSqlServer" Version="6.6.1" />

二、 program.cs 註冊服務與設定組態

program.cs

using Serilog.Events;
using Serilog.Sinks.MSSqlServer;
using Serilog;

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.MSSqlServer(
        builder.Configuration.GetConnectionString("MyRazorPagesContext"),
        sinkOptions: new MSSqlServerSinkOptions { TableName = "Logs", AutoCreateSqlTable = true })
    .CreateLogger();

builder.Host.UseSerilog();

三、建構子注入在 Razor Pages

Index.cshtml.cs

public IndexModel(
  MyRazorPages.Data.MyRazorPagesContext context, 
  ILogger<IndexModel> logger)
{
    _context = context;
    _logger = logger;
}

private readonly ILogger<IndexModel> _logger;

_logger.LogInformation("Log Whaever you want to log.");