Appsettings中的Serilog PushProperty-配置不起作用

时间:2019-03-13 12:43:03

标签: c# asp.net-core serilog

ASP.NET Core 2.2.0 | Serilog.AspNetCore 2.1.1 | Serilog.Sinks.File 4.0.0

我正在Program.cs中初始化Serilog,从appsettings.json中读取配置,并在Startup.cs-> Configure中添加中间件。一些摘要:

Program.cs

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

    try
    {
        Log.Information("Starting web host");
        CreateWebHostBuilder(args).Build().Run();
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "Host terminated unexpectedly");
    }
    finally
    {
        Log.CloseAndFlush();
    }
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseConfiguration(Configuration)
            .UseSerilog();

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment() || env.IsStaging())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
        app.UseRewriter(new RewriteOptions()
            .AddRedirectToWww()
            .AddRedirectToHttps());
    }
    app.UseSession();
    app.UseAuthentication();
    app.UseMiddleware<SerilogAddUserInfo>();

    app.UseStaticFiles();

    app.UseCookiePolicy();
    app.UseMvc();
}

appsettings.json

"Serilog": {
  "MinimumLevel": {
    "Default": "Debug",
    "Override": {
      "Microsoft": "Information",
      "System": "Warning"
    }
  },
  "Enrich": "FromLogContext",
  "WriteTo": [
    {
      "Name": "File",
      "Args": {
        "path": "logs/log.txt",
        "rollingInterval": "Hour",
        "outputTemplate": "{Timestamp:o} [{Level:u3}] [IP {Address}] [Session {Session}] [{SourceContext}] {Site}: {Message}{NewLine}"
      }
    }
  ]
}

SerilogMiddleware.cs

public class SerilogAddUserInfo
{
    private readonly RequestDelegate _next;

    public SerilogAddUserInfo(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        using (LogContext.PushProperty("Address", context.Connection.RemoteIpAddress))
        using (LogContext.PushProperty("Session", context.Session.GetString("SessionGUID") ?? "Unknown"))
        {
            await _next.Invoke(context);
        }
    }
}

在中间件中,我想将一些属性(地址,会话等)推送到日志。当如上所述配置Serilog时,属性在日志中不可见。当我使用Program.cs中的下一个代码段配置Serilog时,它实际上可以工作:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .MinimumLevel.Override("System", LogEventLevel.Information)
    .Enrich.FromLogContext()
    .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Hour,outputTemplate: "{Timestamp:o} [{Level:u3}] [IP {Address}] [Session {Session}] [{SourceContext}] {Site}: {Message}{NewLine}")
    .CreateLogger();

为什么有区别?或者如何在via-appsettings-configured-serilog上使用PushProperty功能?

1 个答案:

答案 0 :(得分:1)

.Enrich.FromLogContext()中初始化Serilog时只需要添加Program.cs

Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        .Enrich.FromLogContext()
        .CreateLogger();

检查 Serilog.AspNetCore 文档中的Inline initialization