我需要将自定义维度记录到我使用 ILogger.BeginScope()
的 Application Insights
。效果很好。即:
using (logger.BeginScope(new Dictionary<string, object> { "key": "value" }))
{
logger.LogInformation("message");
}
我的问题是我需要调用其他类中的其他方法,并且我将 ILogger
注入(inject)到我的所有类中。 那么我怎样才能在我的所有类中保留日志记录范围呢?
我当然可以在所有类中执行ILogger.BeginScope()
,但我需要将自定义属性传递给实际上不需要该信息的类。有我可以使用的模式吗?
最佳答案
如果您在同一执行路径内的多个类中多次调用 BeginScope
,您将获得一个聚合作用域。无需手动传递属性。 ILogger
默认情况下作为单例注入(inject)(请参阅 source code )。
A call to
BeginScope
will put a new item onto that stack, and the adjoiningDispose
will pop it off of that stack.When the logger is invoked via
LogInformation
or otherwise, the data of the current stack object will be copied to write it to the console or whatever output that logger instance is configured to do.
关于azure - ILogger.BeginScope() : persisting scope between calls to other methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74195961/