Serilog表达式模板结合动态属性:如何添加顶级日志属性?
Serilog 保留标准模板并添加特定顶级JSON属性的解决方案
逐个推送LogContext属性,别打包成对象
别把intervalType、method、elapsedTime塞进totalTime对象里,直接单独推送每个属性。Serilog会自动把这些属性作为JSON顶级字段输出,不会嵌到msg里。记得先启用Enrich.FromLogContext(),否则LogContext的属性不会被捕获。
代码示例:using (LogContext.PushProperty("intervalType", "daily")) using (LogContext.PushProperty("method", "ProcessData")) using (LogContext.PushProperty("elapsedTime", 123.45)) { Log.Information("数据处理完成"); }修改表达式模板,显式声明可选属性
在你的标准模板里,用@p['PropertyName']的形式加入可选属性,这样只有当属性存在时才会输出,不会生成多余字段。比如:.WriteTo.Console(new ExpressionTemplate( "{ { ts: @t, lvl: @l, cid: CorrelationId, intervalType: @p['intervalType'], method: @p['method'], elapsedTime: @p['elapsedTime'], msg: @m } }" ))要是用JsonFormatter,记得设置
renderMessage: false避免冗余的消息渲染字段:.WriteTo.Console(new JsonFormatter(renderMessage: false))弃用Compact.JsonFormatter,用标准JsonFormatter
Compact.JsonFormatter自带不少默认冗余字段,直接用标准的JsonFormatter配合自定义表达式模板,能严格控制输出的字段,完全符合你的需求。封装扩展方法简化操作
不想每次都写多个PushProperty?封装个扩展方法一次性推送所有性能属性:public static class LogExtensions { public static IDisposable PushPerformanceProperties(string intervalType, string method, double elapsedTime) { return LogContext.PushProperties( new KeyValuePair<string, object>("intervalType", intervalType), new KeyValuePair<string, object>("method", method), new KeyValuePair<string, object>("elapsedTime", elapsedTime) ); } }使用时一行搞定:
using (LogExtensions.PushPerformanceProperties("hourly", "GenerateReport", 456.78)) { Log.Information("报表生成完成"); }
内容的提问来源于stack exchange,提问作者twreynol
相关产品推荐
相关产品推荐

