0

我正在使用该Gelf.Extensions.Logging包将日志信息从 asp.net core 3 网站发送到 graylog,并且我想要其他字段,例如当前用户名、客户端 ip、用户代理。

在 startup.cs 中,我有以下内容,但我不知道如何将数据添加到AdditionalFields我想要的 - 我什至不确定这是否是正确的地方,因为我看不到如何注入http 上下文在这个早期阶段。

public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
      webBuilder.UseStartup<Startup>()
        .ConfigureLogging((context, builder) => builder.AddGelf(options =>
        {
          options.AdditionalFields["machine_name"] = Environment.MachineName;
          options.AdditionalFields["environment_name"] = context.HostingEnvironment.EnvironmentName;

          options.AdditionalFields["app_version"] = Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
        }));           
    });

我的 appsettings.json 是这样的:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "System": "Warning"
    },
    "GELF": {
      "Host": "graylog",
      "Port": 12202, 
      "Protocol": "HTTP", 
      "LogSource": "DataEntry", 
      "LogLevel": {
        "Default": "Information",
        "Microsoft": "Information",
        "System": "Warning"
      }
    }  
  },
  "AllowedHosts": "*",
   /* snip */
}
4

1 回答 1

0

事实证明,这里推荐的方法是使用像这个示例这样的中间件来添加有关当前请求的信息作为字段:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        // Register the middleware like so:
        app.UseAppEnvironmentInfo();              
    }
}


public static class RequestAppEnvironmentInfoMiddlewareExtensions
{
    public static IApplicationBuilder UseAppEnvironmentInfo(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<AppEnvironmentInfoMiddleware>();
    }
}

public class AppEnvironmentInfoMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly ILogger<AppEnvironmentInfoMiddleware> _logger;

    public AppEnvironmentInfoMiddleware(RequestDelegate next,
        IHttpContextAccessor httpContextAccessor, ILogger<AppEnvironmentInfoMiddleware> logger)
    {
        _next = next;
        _httpContextAccessor = httpContextAccessor;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        using (_logger.BeginScope(("machine_name", Environment.MachineName)))
        using (_logger.BeginScope(("environment_name", context.HostingEnvironment.EnvironmentName)))
        using (_logger.BeginScope(("app_version", Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion)))
        {
            await _next.Invoke(context);
        }
    }
}
于 2020-06-02T06:58:03.133 回答