如何添加自定义维度以在 Nodejs/typescript azure 函数中请求遥测?

Kar*_*lme 6 node.js azure-application-insights azure-functions

目标

请求传入并由 Azure Functions 运行时处理。默认情况下,它会在 Application Insights 中创建一个请求条目和一堆跟踪条目。 我想向该顶级请求项添加自定义维度(基于每个请求),以便稍后使用它进行过滤/分析。

在 Application Insights 上查询 -requests-

在 Application Insights 上查询 -requests-

请求的结果列表,包括自定义维度列

请求的结果列表,包括自定义维度列

Azure Functions 运行时已经添加了一些自定义维度。我想添加一些我自己的。

自定义尺寸展开的图像

方法

我发现的最有前途的方法如下所示(取自此处https://github.com/microsoft/ApplicationInsights-node.js/issues/392

appInsights.defaultClient.addTelemetryProcessor(( envelope, context ) => {
    var data = envelope.data.baseData;
    data.properties['mykey'] = 'myvalue';
    return true;
});
Run Code Online (Sandbox Code Playgroud)

但是,我发现该处理器仅针对我在函数中初始化的请求而调用。例如,如果我向另一个服务发出 HTTP 请求,则该请求的详细信息将通过处理器传递,我可以向其添加自定义属性。但这里main函数好像没有经过。所以我无法添加我的自定义属性。

我也尝试过这个

defaultClient.commonProperties['anotherCustomProp'] = 'bespokeProp2'
Run Code Online (Sandbox Code Playgroud)

同样的问题。自定义属性不会出现在应用程序洞察中。我对此进行了许多变体,看起来 azure-functions 完成的日志记录与我在代码中可以执行的任何操作都是隔离的。

我现在最好的解决方法是手动调用 trackRequest。这没关系,只是我最终在应用程序洞察中将每个请求记录了两次,一次由框架记录,一次由我记录。并且两者都需要具有相同的操作 ID,否则我无法找到关联的跟踪/错误项。所以我不得不以一种稍微有点hacky的方式提取操作Id。这可能没问题,目前我对应用程序洞察的了解还很幼稚。

import { setup, defaultClient } from 'applicationinsights' // i have to import the specific functions, because "import ai from applicationinsights" returns null

// call this because otherwise defaultClient is null.
// Some examples call start(), I've tried with and without this.
// I think the start() function must be useful when you're adding application-insights to a project fresh, whereas I think the azure-functions run-time must be doing this already.
setup()

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    // Extract the operation id from the traceparent as per w3 standard https://www.w3.org/TR/trace-context/.
    const operationId = context.traceContext.traceparent.split('-')[1]
    var operationIdOverride = { 'ai.operation.id': operationId }

    // Create my own trackRequest entry
    defaultClient.trackRequest({
      name: 'my func name',
      url: context.req.url.split('?')[0],
      duration: 123,
      resultCode: 200,
      success: true,
      tagOverrides: operationIdOverride,
      properties: {
        customProp: 'bespokeProp'
      }
    })

Run Code Online (Sandbox Code Playgroud)

梦想

我们的 C# 兄弟似乎有一系列选项,例如Activity.Current.tags添加 TelemetryInitializer 的能力。然而,看起来我想做的事情是受支持的,我只是找不到正确的命令组合!javascript/typescript/nodejs 是否有类似的东西,我可以在每个请求的基础上添加一个标签?沿着context.traceContext.attributes['myprop'] = 'myValue'

选择

或者,使用我自己的 TelemetryClient(而不是 defaultClient)使用 trackRequest、trackTrace、trackError 等来检测我的代码,这并不是一项非常大的工作,并且应该工作得很好 - 这会更明确。我应该这样做吗?有没有办法禁用天蓝色功能跟踪 - 或者也许我只是将其保留为并行运行的东西。