如何在 Azure Functions 中使用结构化日志记录

Jim*_*eil 4 logging azure azure-functions

我在 Azure 函数中使用相对较新的 ILogger(相对于 TraceWriter)选项,并尝试了解如何捕获日志。

这是我的功能:

    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, ILogger log)
    {
        log.LogTrace("Function 1 {level}", "trace");
        log.LogWarning("Function 1 {level}", "warning");
        log.LogError("Function 1 {level}", "error");

        return req.CreateResponse(HttpStatusCode.OK, "Success!!!!");
    }
Run Code Online (Sandbox Code Playgroud)

当我查看服务器日志时,LogFiles 目录具有层次结构。

在此输入图像描述

黄色突出显示的文件包含我的日志语句:

2017-08-19T13:58:31.814 Function started (Id=d40f2ca6-4cb6-4fbe-a05f-006ae3273562)
2017-08-19T13:58:33.045 Function 1 trace
2017-08-19T13:58:33.045 Function 1 warning
2017-08-19T13:58:33.045 Function 1 error
2017-08-19T13:58:33.075 Function completed (Success, Id=d40f2ca6-4cb6-4fbe-a05f-006ae3273562, Duration=1259ms)
Run Code Online (Sandbox Code Playgroud)

结构化目录此处不包含任何内容,但在我的真实功能应用程序目录中似乎有各种“codeddiagnostic”日志语句。

我应该在这里期待什么?最终,我希望有一个单一的接收器来记录我的所有应用程序组件,并全面利用结构化日志记录。

Pac*_*ruz 5

从 Azure Functions 收集结构化日志记录的最佳方法是使用 Application Insights。如果您定义了您的 Logger 基于 ILogger,您可以定义一个模板来指定您想要记录的属性。然后,在 Application Insights 跟踪中,使用 Application Insights 查询语言(又名 Kusto),您可以访问名称为 customDimensions.prop__{name} 的每个属性的值。

您可以在这篇文章中找到如何使用 Azure Functions v2 执行此操作的示例https://platform.deloitte.com.au/articles/corlated-structed-logging-on-azure-functions


Kel*_*lux 5

仅供参考:在隔离模式(.NET5 和 .NET6)下运行的 Azure Functions 不支持使用 DI 中或 FunctionContext 中提供的 ILogger 进行结构化日志记录。截至 2021 年 11 月,有一个关于它的开放错误:https://github.com/Azure/azure-functions-dotnet-worker/issues/423

据我了解,发生该错误的原因是所有 ILogger 调用都通过主机和隔离函数之间的 GRPC 连接,并且在此过程中消息被格式化,而不是发送原始格式和参数。用于记录结构化日志的 Azure Insights 连接在主机上运行,​​并且仅接收最终消息。

我计划研究一些解决方法,在隔离的进程中直接访问 Azure Insights。如果有效,我将在上面链接的错误的评论中发布解决方法。