appiltings-Serilog PushProperty配置不起作用

问题描述 投票:3回答:1

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的可能性?

c# asp.net-core serilog
1个回答
1
投票

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

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

在Serilog.AspNetCore文档中检查Inline initialization

© www.soinside.com 2019 - 2024. All rights reserved.