Serilog.AspNetCore v9.0.0中无法显示EventId子属性的解决方法
Serilog.AspNetCore v9.0.0 提取EventId.Id的解决方案
问题原因
直接使用{EventId.Id}或{EventId.Name}显示空字符串,是因为Serilog默认未自动解构EventId对象的内部属性,导致模板无法直接访问其成员。
解决方法
方法1:添加EventId解构规则
在Logger配置中,通过Destructure.ByTransforming显式解析EventId的属性,之后就能在输出模板中直接使用{EventId.Id}:
using Serilog; using Serilog.Events; var builder = WebApplication.CreateBuilder(args); builder.Host.UseSerilog((context, config) => { config .Destructure.ByTransforming<EventId>(e => new { e.Id, e.Name }) // 解构EventId对象 .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {EventId.Id}: {Message:lj}{NewLine}{Exception}") .ReadFrom.Configuration(context.Configuration); }); var app = builder.Build(); // ... 其他中间件配置 app.Run();
方法2:直接访问Properties字典中的EventId属性
如果不想修改解构规则,可以在输出模板中通过Properties字典直接访问EventId的Id成员:
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Properties[EventId].Id}: {Message:lj}{NewLine}{Exception}")
方法3:使用Serilog表达式模板
表达式模板支持更灵活的属性访问,无需额外解构配置:
.WriteTo.Console(new ExpressionTemplate( "[{@Timestamp:HH:mm:ss} {@Level:u3}] {@EventId.Id}: {@Message:lj}{NewLine}{@Exception}"))
以上三种方法都能让日志输出仅显示EventId的数值(如"14")。
内容的提问来源于stack exchange,提问作者JazzyHacker
相关产品推荐
相关产品推荐

