首页 > 解决方案 > 使用 DI 的 Azure Functions V3 ILogger - 来自记录器的消息不在跟踪中

问题描述

在我的 Azure Function 中,我尝试使用 DI 容器进行日志记录;但是我无法让记录器显示日志流中的消息或 Application Insights 中的跟踪。我创建了一个最小的代码示例项目,我正在使用此处显示的 Azure 门户(代码 + 测试)进行测试。我试过使用 Serilog 相同的结果。我尝试从 Function1 中删除 log 参数 - 然后我没有收到任何错误或消息,我认为我错过了一些简单/明显的东西,但我被卡住了。

namespace LoggingApiTest {
public class Function1 {
    private readonly ILogger<Function1> logger;

    public Function1(ILogger<Function1> logger)
    {
        this.logger = logger;
        logger.LogInformation("In Function1 ctor using DI created Logger");
    }

    [FunctionName("Function1")]
    public IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "Test")] HttpRequest req,
        ILogger log) {
        logger.LogInformation("Hello from DI Logger");
        log.LogInformation("Hello from logger passed as parameter");
        return new OkObjectResult("Hello");
    }
}

}

启动

namespace LoggingApiTest {
public class Startup : FunctionsStartup {
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddLogging();

    }
}

}

主机.json

enter code here{
"version": "2.0",
"logging": {
  "applicationInsights": {
    "samplingSettings": {
      "isEnabled": true,
      "excludedTypes": "Request"
    },
    "logLevel": {
      "default": "Information"
    }
  }
}

}

日志流显示2021-07-16T12:59:50.705 [Information] Executing 'Function1' (Reason='This function was programmatically called via the host APIs.', Id=b8238346-7ff7-450d-a7f0-abc8f1a210fa) 2021-07-16T12:59:50.705 [Information] Hello from logger passed as parameter 2021-07-16T12:59:50.705 [Information] Executed 'Function1' (Succeeded, Id=b8238346-7ff7-450d-a7f0-abc8f1a210fa, Duration=1ms)

标签: azuredependency-injectionazure-functionsilogger

解决方案


host.json文件的日志记录部分,尝试使用logLevel. 这应该启用 a logLevelofInformation及以上的日志记录。

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "LoggingApiTest": "Information"
    }
  }
}

https://github.com/Azure/azure-functions-host/issues/4425#issuecomment-492678381


推荐阅读