简体   繁体   English

Serilog 动态丰富上下文

[英]Serilog Dynamically enrich a context

Is there any possibility to dynamically override or extend the log template in Serilog?是否有可能动态覆盖或扩展 Serilog 中的日志模板?

I have a parser class which parses XML line by line and I want to extend the log entry with the line number.我有一个解析器 class 逐行解析 XML ,我想用行号扩展日志条目。 I have already written an enricher that does that, but I have to globally override the default logger at the start of the function and reset it at the end, which is difficult to even look at (from a programming perspective):D我已经编写了一个可以做到这一点的浓缩器,但是我必须在 function 的开头全局覆盖默认记录器并在最后重置它,这甚至很难看(从编程的角度来看):D

What are the other options with Serilog or have I missed something? Serilog 的其他选择是什么,或者我错过了什么?

After some more digging I finally found a solution that fit my needs.经过一番挖掘,我终于找到了适合我需求的解决方案。

I used the LogContext.PushProperty mechanism to push the XmlReader (or rather a wrapper object, because the type-matching with the destructuring is exact and XmlReader is a factory which returns many different classes) into the LogContext and added a custom destructuring to LoggerConfiguration to detect objects of that wrapper type and then format it to my liking.我使用LogContext.PushProperty机制将XmlReader (或者更确切地说是一个包装器 object,因为与解构的类型匹配是精确的,并且XmlReader是一个返回许多不同类的工厂)到LogContext并添加了一个自定义解构到LoggerConfiguration检测该包装类型的对象,然后根据我的喜好对其进行格式化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM