3

我使用 netcore2.0 并为中间件类中的每个请求设置 log4net.LogicalThreadContext 属性“requestid”以进行日志记录。

log4net.LogicalThreadContext.Properties["requestid"] = Guid.NewGuid().ToString("N");

但是“Microsoft.AspNetCore.Hosting.Internal.WebHost”类在记录行时不显示此属性。

我不知道如何为“Microsoft.AspNetCore.Hosting.Internal.WebHost”设置 log4net.LogicalThreadContext.Propery["requestid"]。

我希望从头到尾绑定所有请求日志。有没有人有任何可能有帮助的见解?

问候!

更新:这是代码

using Microsoft.Extensions.Logging;
...

public static ILoggerProvider Log4NetProvider;

public static void Main(string[] args)
    {

#if DEBUG
        Log4NetProvider = new Log4NetProvider("log4net.Debug.config", ((o, 
exception) => exception.Message));
#else
        Log4NetProvider = new Log4NetProvider("log4net.Release.config", ((o, 
exception) => exception.Message));
#endif
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())                
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddProvider(Log4NetProvider);                   
            })
            .ConfigureServices(services =>
            {
                services.AddAutofac();
            })
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();
        host.Run();

在 Startup.cs Configure(IApplicationBuilder app, IHostingEnvironment env) 我已经设置为第一件事。

app.UseMiddleware<Log4NetRequestIdMiddleware>();

public class Log4NetRequestIdMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        log4net.LogicalThreadContext.Properties["requestid"] = Guid.NewGuid().ToString("N");
        await _next(context);
    }
}

Log4net 配置文件>

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="C:\log\applog.log" />
    <rollingStyle value="Size"/>
    <maxSizeRollBackups value="500"/>
    <maximumFileSize value="5MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%utcdate|%-5level|%logger|%property{requestid}| %message %exception%newline" />
    </layout>
  </appender>
  <root>
    <level value="ALL" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

Fileappender.log 中的其他示例(粗体标记 RequestId)

2018-04-10 14:02:28,664|信息|Microsoft.AspNetCore.Hosting.Internal.WebHost| (空) | 请求开始 HTTP/1.1 GET http://localhost ...
2018-04-10 14:02:28,956|INFO| Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker| cfb2709e3b4f40559c365ecbb08a7746 | 执行动作方法 Controllers.HealtCheckStatusController.GetHealthCheckStatus 2018-04-10 14:02:29,486|INFO| Microsoft.AspNetCore.Mvc.Internal.ObjectResultExecutor| cfb2709e3b4f40559c365ecbb08a7746 | 执行 ObjectResult,写入值 Microsoft.AspNetCore.Mvc.ControllerContext。
2018-04-10 14:02:29,510|信息| Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker| cfb2709e3b4f40559c365ecbb08a7746| 执行动作 Controllers.HealtCheckStatusController.GetHealthCheckStatus 在 564.464ms 2018-04-10
14:02:29,520|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost| (空) | 请求在 858.9575 毫秒内完成 200 应用程序/json;字符集=utf-8

4

2 回答 2

3

为什么WebHost记录器不显示属性

WebHostlogger 记录两条消息 - 请求开始消息和请求完成消息。

请求启动消息看不到requestid属性,因为在设置属性的类中WebHost包含在管道中的第一个中间件之前运行并记录消息。Startuprequestid

请求完成的消息没有看到requestid属性,因为(我猜)WebHost记录器不在log4net.LogicalThreadContext. 如果在控制器操作中设置它,就好像Log4NetRequestIdMiddleware记录器不会看到属性。requestid

可能的解决方案

由于logger从命名空间WebHost的类深处记录消息,因此没有任何明确的扩展点来注入将设置属性的代码。所以,我认为您可以像记录器一样在中间件中记录信息:HostingApplicationDiagnosticsMicrosoft.AspNetCore.Hosting.InternalrequestidWebHost

public async Task Invoke(HttpContext context)
{
    var logger = httpContext.RequestServices.GetRequiredService<ILogger<Log4NetRequestIdMiddleware>>();
    log4net.LogicalThreadContext.Properties["requestid"] = Guid.NewGuid().ToString("N");
    
    var request = context.Request;
    string logMsg = string.Format(
            CultureInfo.InvariantCulture,
            "Request starting {0} {1} {2}://{3}{4}{5}{6} {7} {8}",
            request.Protocol,
            request.Method,
            request.Scheme,
            request.Host.Value,
            request.PathBase.Value,
            request.Path.Value,
            request.QueryString.Value,
            request.ContentType,
            request.ContentLength);
    
    logger.LogDebug(logMsg);

    await _next(context);
}
于 2018-05-04T14:09:02.467 回答
0

你可以看看这个 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1#logging-providers

创建自己的 LogProvider,像这样清除日志提供程序。

            services.AddLogging(config =>
            {
                config.ClearProviders();
            });

            loggerFactory.AddLog4Net();

本文讲述如何创建 log4net Logger。 https://dotnetthoughts.net/how-to-use-log4net-with-aspnetcore-for-logging/

于 2020-07-24T00:44:56.023 回答