使用ILogger<>的BeginScope添加自定义属性不生效问题
日志Scope自定义属性不显示问题解决
尝试通过BeginScope给日志添加全局自定义属性,但输出的日志中看不到这些附加的Scope属性,仅显示结构化日志本身的内容。
代码示例
var builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder .Services .AddLogging(c => c.AddJsonConsole(y => y.JsonWriterOptions = new() { Indented = true })); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; app.MapGet("/weatherforecast", async (ILogger<Program> logger) => { var state = new Dictionary<string, object>() { { "CustPropOne", "123456-7890123" }, { "CustPropTwo", "blah blah blah" }, { "CustNumber", 12345 } }; using (logger.BeginScope(state)) { logger.LogInformation("API 1 {One}", 1); var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast ( DateOnly.FromDateTime(DateTime.Now.AddDays(index)), Random.Shared.Next(-20, 55), summaries[Random.Shared.Next(summaries.Length)] )) .ToArray(); return forecast; } }) .WithName("GetWeatherForecast") .WithOpenApi(); app.Run(); record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) { public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); }
实际输出
{ "EventId": 0, "LogLevel": "Information", "Category": "Program", "Message": "API 1 1", "State": { "Message": "API 1 1", "One": 1, "{OriginalFormat}": "API 1 {One}" } }
解决方法
问题出在JsonConsole日志提供器的默认配置:默认不包含Scope信息,需要显式开启。
修改AddJsonConsole的配置,添加IncludeScopes = true:
builder .Services .AddLogging(c => c.AddJsonConsole(y => { y.JsonWriterOptions = new() { Indented = true }; // 开启Scope包含 y.IncludeScopes = true; }));
修改后,日志输出会新增Scope字段,包含所有自定义属性:
{ "EventId": 0, "LogLevel": "Information", "Category": "Program", "Message": "API 1 1", "State": { "Message": "API 1 1", "One": 1, "{OriginalFormat}": "API 1 {One}" }, "Scope": [ { "CustPropOne": "123456-7890123", "CustPropTwo": "blah blah blah", "CustNumber": 12345 } ] }
如果需要将Scope属性合并到State或根对象中,可以进一步配置JsonConsoleFormatterOptions自定义Scope格式化逻辑,但默认的单独Scope字段已经能清晰区分日志本身属性和全局Scope属性,满足多数场景需求。
内容的提问来源于stack exchange,提问作者Dario Griffo
相关产品推荐
相关产品推荐

