我使用 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