azure - 将元数据添加到 Azure 函数中的跟踪

标签 azure azure-functions azure-application-insights azure-function-app .net-core-2.0

我有一个 Azure 函数(.NET core 2.0),它在 ADO 存储库中的每个 PR 上运行。 我想将 PR-ID 作为元数据添加到 Azure 函数记录的每个跟踪中。 (我正在使用 Azure 应用程序洞察实例中的 traces 表查看日志)

Azure 函数通过以下方式记录跟踪:

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, ILogger log, ExecutionContext context)
{
  logger.LogInformation("Trace Message");
}

如何向每个跟踪添加额外的元数据?

最佳答案

是的,这是可能的。

选项 1:AsyncLocal 的帮助下使用遥测初始化程序:

    public class CustomTelemetryInitializer : ITelemetryInitializer
    {
        public static AsyncLocal<string> MyValue = new AsyncLocal<string>();

        public void Initialize(ITelemetry telemetry)
        {
            if (telemetry is ISupportProperties propertyItem)
            {
                propertyItem.Properties["myProp"] = MyValue.Value;
            }
        }
    }

您可以在函数中设置 AsyncLocal 的值,如下所示:

        [FunctionName("Function")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            HttpRequest req,
            ILogger log)
        {
            var name = req.Query["name"];

            CustomTelemetryInitializer.MyValue.Value = name;

            log.LogInformation("C# HTTP trigger function processed a request.");

            return new OkObjectResult($"Hello, {name}");
        }

当您运行该函数时,您可以在门户中看到信息:

enter image description here

您可以在 this repo 找到完整代码

现在,处理您的评论。是的,你需要一些额外的东西。 ITelemetryInitializer 实例需要使用依赖注入(inject)来注册。这是在 Startup 类中完成的,如 documentation 中所述。 :

    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.Azure.Functions.Extensions.DependencyInjection;
    using Microsoft.Extensions.DependencyInjection;

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

    namespace FunctionApp
    {
        public class Startup : FunctionsStartup
        {
            public override void Configure(IFunctionsHostBuilder builder)
            {
                builder.Services.AddSingleton<ITelemetryInitializer, CustomTelemetryInitializer>();
                builder.Services.AddLogging();
            }
        }
    }

注册后,Application Insights SDK 将使用 CustomTelemetryInitializer

选项 2 另一个选项不涉及任何 TelemetryInitializer,但只能将属性添加到由 Azure Function App Insights 集成添加的生成的 RequestTelemetry。这是通过利用当前 TelemetryRequest 存储在 HttpContext 中的事实来完成的:

       [FunctionName("Function")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            HttpRequest req,
            ILogger log)
        {
            var name = req.Query["name"];

            CustomTelemetryInitializer.MyValue.Value = name;

            log.LogInformation("C# HTTP trigger function processed a request.");

            var telemetryItem = req.HttpContext.Features.Get<RequestTelemetry>();
            telemetryItem.Properties["SetInFunc"] = name;

            return new OkObjectResult($"Hello, {name}");
        }

这也会显示在门户中:

enter image description here

仅在Request中添加上下文有问题吗?可能会,但请注意,您可以查询所有相关的遥测数据并了解涉及的上下文,例如:

union (traces), (requests), (dependencies), (customEvents), (exceptions)
| extend itemType = iif(itemType == 'availabilityResult',itemType,iif(itemType == 'customEvent',itemType,iif(itemType == 'dependency',itemType,iif(itemType == 'pageView',itemType,iif(itemType == 'request',itemType,iif(itemType == 'trace',itemType,iif(itemType == 'exception',itemType,"")))))))
| extend prop = customDimensions.SetInFunc
| where ((itemType == 'trace' or (itemType == 'request' or (itemType == 'pageView' or (itemType == 'customEvent' or (itemType == 'exception' or (itemType == 'dependency' or itemType == 'availabilityResult')))))))
| top 101 by timestamp desc

将显示:

enter image description here

来自同一调用的所有遥测数据都将具有相同的 operation_Id

关于azure - 将元数据添加到 Azure 函数中的跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58709756/

相关文章:

c# - 本地运行 Azure 函数时出现来自 WebJobsBuilderExtensions 的 StackOverFlow 异常

azure - 自定义域以及如何通过 http ://访问网站

azure - 上传到 Azure Functions 的 .css 文件的路径?

python - 单个Python脚本的Azure函数部署以及Azure Functions中requirements.txt的安装过程

asp.net - 无法将 ASP.NET Core Web 应用程序与 Application Insights 连接

Azure Application Insights - 不记录高流量情况下的所有请求

azure - 在 ADF 管道中映射数据流与 SQL 存储过程

azure - Nginx 路由忽略路径规则之后的任何内容

python - 如何在我的 Azure Function App 中实现负载均衡器?

azure - 使用 Azure Application Insights REST API (https ://dev. applicationinsights.io) 读取自定义事件/指标