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

问题描述

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

但是,目前基础知识似乎不起作用。

我正在尝试使用 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.Log@R_789_4045@ion("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.Log@R_789_4045@ion("A log from within scope {SomeId}");
        }

    }
}

我错过了什么?!

谢谢。

解决方法

据我所知,当在 dictionary type 方法中使用 logger.BeginScope 时,集合中的 key-value pair 将作为 custom properties(doc是 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());
        }