在AspNet Core项目中集成Serilog

发布时间 2023-04-04 18:28:53作者: toyz、

1.引入Nuget包 Serilog.AspNetCore

2.配置Serilog

using Serilog;
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console() // 添加console日志输出
    .WriteTo.Debug() // 添加debug日志输出
    .CreateLogger();
try
{
    Log.Information("Starting web application");
    var builder = WebApplication.CreateBuilder(args);
    builder.Host.UseSerilog(); // <-- Add this line
    var app = builder.Build();
    app.MapGet("/", () => "Hello World!");
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}

builder.Host.UseSerilog(); 通过Serilog管道重定向所有日志时间,删除默认记录器的剩余配置进行清理。

3.使用UseSerilogRequestLogging

app.UseStaticFiles();
// 使用Serilog.AspNetCore封装好的UseSerilogRequestLogging中间件
// 不会记录出现在它之前的组件 比如UseStaticFiles
app.UseSerilogRequestLogging();
// Other app configuration
  • 这种模式的优点是减少了每个 HTTP 请求需要构建、传输和存储的日志事件的数量。在同一事件上拥有多个属性还可以使请求详细信息和其他数据的关联更加容易。

    默认情况下,将添加以下请求信息作为属性:

    • RequestMethod
    • RequestPath
    • StatusCode
    • Elapsed

也可以修改配置模板

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);
    };
});