如何记录 Azure Function App 依赖项的结果?

How do I log results from an Azure Function App dependency?

我有一个包含以下文件的 Azure Function App 项目:

Startup.cs:注册一个依赖

[assembly: FunctionsStartup(typeof(MyLoggingFunction.Startup))]

namespace MyLoggingFunction
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddScoped<MyService>();
        }
    }
}

MyService.cs: 写入日志消息

namespace MyLoggingFunction
{
    public class MyService
    {
        private readonly ILogger<MyService> logger;

        public MyService(ILogger<MyService> logger)
        {
            this.logger = logger;
        }

        public void Go()
        {
            this.logger.LogInformation("MyService.Go");
        }
    }
}

MyFunction.cs:实际函数;使用 MyService

namespace MyLoggingFunction
{
    public class MyFunction
    {
        private readonly MyService myService;

        public MyFunction(MyService myService)
        {
            this.myService = myService;
        }

        [FunctionName("MyFunction")]
        public IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            this.myService.Go();
            log.LogInformation("All done");
            return new OkObjectResult("Done.");
        }
    }
}

这是函数成功运行后在 Azure 中可见的输出。请注意,缺少注入依赖项的日志消息:

如何从依赖项中获取日志消息以显示为内置日志记录的一部分?

将日志记录级别条目添加到 host.json :

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

您必须将要允许日志记录的 类 and/or 命名空间列入白名单。示例 hosts.json 文件:

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

这是documented as an issue on the azure-function-host GitHub repository