azure - ILogger.BeginScope() : persisting scope between calls to other methods

标签 azure .net-core azure-application-insights

我需要将自定义维度记录到我使用 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 )。

另请参阅Since ILogger<T> is a singleton, how different threads can use BeginScope() without affecting others?

A call to BeginScope will put a new item onto that stack, and the adjoining Dispose 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/

相关文章:

azure - .NET-Core 作为 Azure AppService 和本地的常见功能即服务功能

asp.net-mvc - Azure:升级到 Azure SDK v2.1

api - 如何在 Azure APIM 中获取 API 的订阅者 ID?

c# - Swagger 响应描述未显示

c# - 确保使用有效的 IComparer

azure - 如何将 Application Insights 从一个区域迁移到另一区域?

Azure函数调用其他API,失败并显示 'A connection attempt failed because the connected party did not properly respond after a period of time,,,'

c# - HttpClient/HttpRequestMessage 接受头参数不能有空格

javascript - 应用程序洞察记录查看的列表项?

azure - 如何使用 Azure Kusto 从列中的拆分部分获取唯一 ID