Serilog 条件模板 headers

Serilog conditional template headers

有没有办法在 Serilog 模板中有条件地包含字符串? 例如,

_logger.Information("Event: {evt} Description: {dsc}", evt, dsc}

如果 dsc 为 null 或为空,如何省略 "Description:" 字符串?

message template肯定是方程中的不动点

如果description是你的辅助字段,你可以

_logger.ForContext("Description",dsc).Information("Event: {evt}", evt}

...如果您这样做,请务必在日志呈现格式字符串中包含 {Properties} 以包含实际消息模板中未使用的诸如此类的上下文字段。

除此之外,你还剩下一个不起眼的人 if:

if(desc!=null)
    _logger.Information("Event: {evt} Description: {dsc}", evt, dsc}
else
    _logger.Information("Event: {evt}", evt);

请注意,由于显而易见的原因,这将在消息中产生不同的消息模板 ID,这可能是更喜欢前者的原因。

(也不可能是三元运算符而不是 if - 这会让 运行 你陷入 Serilog Analyzer 的麻烦)