自定义 ILogger 范围值未按预期工作

Custom ILogger scope values not working as expected

我在这里遗漏了一些东西,因为许多文章都表明它应该有效。计划是创建一个自定义记录器实现,这样我就可以以结构化的方式存储各种值。

但是,目前基础知识似乎还行不通。

我正在尝试使用 ILogger 内的范围来设置某些值,例如transactionId.

我正在使用 Azure Functions。在我添加的启动中

public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddLogging();

效果很好。在我正在尝试的功能中..

public class Test_Http
{
    private readonly ILogger logger;

    public Test_Http(ILogger<TestHttp> log)
    {
        this.logger = log;
    }


    [FunctionName("TestHttp")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        // This works fine, SomeId is replace.
        // When using a custom logger I can see 2 values in the state.
        logger.LogInformation("Message '{SomeId}'", "TheID");


        using (logger.BeginScope(new Dictionary<string, object>
        {
            ["SomeId"] = "SOME ID"
        }))
        {
            // SomeId is not replaced as I would expect.
            // State in a custom logger contains a single value.
            logger.LogInformation("A log from within scope {SomeId}");
        }

    }
}

我错过了什么?!

谢谢。

据我所知,当在 logger.BeginScope 方法中使用 dictionary type 时,集合中的 key-value pair 将作为 custom properties 添加到应用程序洞察遥测中(文档是 here)。它不会替换您示例中的 {SomeId}

如果要替换它,需要在logger.LogInformation方法中显式添加一个值。例如:

        Dictionary<string, object> a = new Dictionary<string, object>
        {
            //SomeId only adds as a custom property for telemetry data.
            ["SomeId"] = "SOME ID"
        };

        using (logger.BeginScope(a))
        {
            //you need to explicitly add a value to replace {SomeId}
            logger.LogInformation("A log from within scope {SomeId}",a.Values.First());
        }