【问题标题】:Adding Custom Dimension to Request Telemetry - Azure functions将自定义维度添加到请求遥测 - Azure 函数
【发布时间】:2021-07-14 04:38:32
【问题描述】:

我正在使用 v2.x 创建一个新的 Function 应用,并且我正在集成 Application Insights 以实现请求日志记录,因为 Azure Function 现在已与 App Insights 集成(如文档 link 中所述)。我需要做的是在 Application Insights 请求遥测的自定义维度中记录几个自定义字段。是否可以不使用自定义请求日志记录(使用TrackRequest 方法)

【问题讨论】:

标签: azure azure-functions azure-application-insights


【解决方案1】:

关于添加自定义属性,可以参考这篇教程:Add properties: ITelemetryInitializer。下面是我测试的一个HTTP触发函数。

public static class Function1
{
    private static string key = "Your InstrumentationKey";
    private static TelemetryClient telemetry = new TelemetryClient() { InstrumentationKey = key };
    [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        if (!telemetry.Context.Properties.ContainsKey("Function_appName"))
        {
            telemetry.Context.Properties.Add("Function_appName", "testfunc");
        }
        else
        {
            telemetry.Context.Properties["Function_appName"] = "testfunc";
        }

        telemetry.TrackEvent("eventtest");
        telemetry.TrackTrace("tracetest");

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        return name != null
            ? (ActionResult)new OkObjectResult($"Hello, {name}")
            : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
    }
}

运行此功能后,转到 Application Insights Search 可以检查数据或转到 Logs(Analytics)。

更新:

【讨论】:

  • 正如我所提到的,我想要将自定义属性添加到请求而不是事件中。上面的屏幕截图显示了为事件而不是请求创建的自定义属性
  • @Silly John,请求也可以添加,检查我的更新。
  • 我在帖子中提到我不想进行自定义请求日志记录。在上述细节中,您明确地启动和停止操作,这实际上是自定义请求日志记录。
  • 为什么我们需要将其声明为成员new TelemetryClient() 为什么我们不能简单地使用ILogger 而无需做任何事情telemetryclient
【解决方案2】:

您应该在函数应用程序中使用 ITelemetry Initializer(它可以将自定义维度添加到指定的遥测,例如仅用于请求),请按照以下步骤操作:

1.在Visual Studio中,创建一个函数应用(在我的测试中,我创建了一个blob触发函数),并安装以下nuget包:

Microsoft.ApplicationInsights, version 2.10.0

Microsoft.NET.Sdk.Functions, version 1.0.29

2.然后在Function1.cs中,编写如下代码:

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.IO;

[assembly: WebJobsStartup(typeof(FunctionApp21.MyStartup))]
namespace FunctionApp21
{
    public static class Function1
    {


        [FunctionName("Function1")]
        public static void Run([BlobTrigger("samples-workitems/{name}", Connection = "AzureWebJobsStorage")]Stream myBlob, string name, ILogger log)
        {
            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
        }
    }

    internal class MyTelemetryInitializer : ITelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {           

            //use telemetry is RequestTelemetry to make sure only add to request
            if (telemetry != null && telemetry is RequestTelemetry && !telemetry.Context.GlobalProperties.ContainsKey("my_custom_dimen22"))
            {
                telemetry.Context.GlobalProperties.Add("my_custom_dimen22", "Hello, this is custom dimension for request!!!");
            }
        }
    }

    public class MyStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.Services.AddSingleton<ITelemetryInitializer, MyTelemetryInitializer>();

        }
    }
}

3.将其发布到 azure,然后导航到 azure 门户 -> 发布的函数应用 -> 监控 -> 添加应用洞察。

4.从 azure 运行函数。并等待几分钟 -> 导航到应用洞察门户,查看遥测数据,您可以看到自定义维度仅用于请求遥测:

【讨论】:

  • 但这在本地不起作用,是吗?这将不难管理
  • @SillyJohn,给你更新一下,代码现在可以在本地和 azure 门户上运行。
【解决方案3】:

其他解决方案并没有完全回答这个问题,即如何将自定义属性添加到请求遥测中。有一个非常简单的解决方案,在您的函数代码中添加以下内容:

Activity.Current?.AddTag("my_prop", "my_value");

你需要:

using System.Diagnostics;

这可以是每个函数调用/请求的动态,而不是固定的全局属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-26
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多