我想要获取 ASP.Net Core 服务中每条日志消息中记录的某些关键信息(服务名称、服务版本、主机名等)。
我有以下代码:
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (host.Services.GetRequiredService<ILogger<Program>>().BeginScope("ServiceName: {0}", "bob-service"))
{
host.Run();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(builder =>
{
builder.AddConsole(o => o.IncludeScopes = true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
由此我得到以下日志记录:
info: Microsoft.Hosting.Lifetime[0]
=> ServiceName: bob-service
Now listening on: http://localhost:5002
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[102]
=> ConnectionId:0HLSO8706NGBN => RequestPath:/ RequestId:0HLSO8706NGBN:00000001, SpanId:|aa5794ba-408ad22a63064421., TraceId:aa5794ba-408ad22a63064421, ParentId: => Middleware_Scope => /Index
Executed handler method OnGet, returned result .
请注意如何ServiceName
仅出现在主机级日志记录中。请求级别的日志记录确实not包括它。
是否有一种机制可以设置范围every来自 ASP.Net Core 的日志消息。
我尝试添加一个中间件来执行此操作,它基本上可以工作,但日志记录不会出现在"Microsoft.AspNetCore.Hosting.Diagnostics"
日志消息(尽管据我所知它出现在其他所有内容上)。
app
.Use(async (context, next) =>
{
// Middleware to add scoped values to log messages.
var logger = context.RequestServices.GetRequiredService<ILogger<Startup>>();
using (logger.BeginScope("ServiceName: {0}", "bob-service")))
{
await next();
}
});
EDIT
即使使用上述中间件,也会记录来自Microsoft.AspNetCore.Hosting.Diagnostics
记录器不包含作用域字段。例如,请注意在第二条日志消息中,Middleware_Scope
不出现范围消息。
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[6]
=> ConnectionId:0HLSOTDVELPJA => RequestPath:/css/site.css RequestId:0HLSOTDVELPJA:00000001, SpanId:|2fbd556d-44cc7c919266ccaf., TraceId:2fbd556d-44cc7c919266ccaf, ParentId: => Middleware_Scope
The file /css/site.css was not modified
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
=> ConnectionId:0HLSOTDVELPJD => RequestPath:/js/site.js RequestId:0HLSOTDVELPJD:00000001, SpanId:|2fbd5570-44cc7c919266ccaf., TraceId:2fbd5570-44cc7c919266ccaf, ParentId:
Request finished in 29.8413ms 304 application/javascript