Microsoft.AspNetCore.Hosting.Internal.WebHost和log4net.LogicalThreadContext.Properties [" requestid"]

时间:2018-04-19 11:55:58

标签: c# log4net asp.net-core-2.0 web-hosting threadcontext

我使用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中 配置(IApplicationBuilder应用程序,IHostingEnvironment环境)我已经设置为第一件事。

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配置文件&gt;

<?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 | INFO | Microsoft.AspNetCore.Hosting.Internal.WebHost | (null) |请求启动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 | INFO | Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker |的 cfb2709e3b4f40559c365ecbb08a7746 |执行动作Controllers.HealtCheckStatusController.GetHealthCheckStatus in 564.464ms
  2018-04-10 14:02:29,520 | INFO | Microsoft.AspNetCore.Hosting.Internal.WebHost | (null) |要求以858.9575ms 200申请/ json完成;字符集= UTF-8

2 个答案:

答案 0 :(得分:1)

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

WebHost记录器记录两条消息 - 请求启动消息和请求已完成消息。

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

请求已完成消息未看到requestid属性,因为(我猜)WebHost记录器超出log4net.LogicalThreadContext。就像Log4NetRequestIdMiddleware logger在控制器操作中设置requestid属性一样。

可能的解决方案

由于WebHost logger会在Microsoft.AspNetCore.Hosting.Internal命名空间的HostingApplicationDiagnostics类深处记录消息,因此没有任何明确的扩展点可以注入设置requestid属性的代码。 所以,我认为您可以在中间件中记录信息,就像WebHost logger:

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

答案 1 :(得分: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/