【问题标题】:How to get Application Insights operation id in javascript?如何在 javascript 中获取 Application Insights 操作 ID?
【发布时间】:2021-02-03 17:26:35
【问题描述】:

我有一个用 javascript 编写的 Azure Function 应用,它集成了 Application Insights:

const AppInsights = require("applicationinsights");

AppInsights.setup(appInsightsInstrumentationKey);
AppInsights.defaultClient.context.tags[
    AppInsights.defaultClient.context.keys.cloudRole
        ] = "My back-end";
AppInsights.start();

模块版本为1.7.4。

我确实需要访问当前操作 ID 以将其发送到我的自定义日志,以便与 Azure 中的 AI 日志相关联。在我的函数中,我尝试了这个:

var telemetry = appInsights.defaultClient;
var oid = telemetry.context.tags["ai.operation.id"]; // does not work
var oid = telemetry.context.operation.id; // does not work

尽管如此,AI 还是以某种方式收集了它,因此我可以在 Azure 门户中看到它:

如何在我的 Azure 函数中在运行时访问 operation_id 值?

【问题讨论】:

    标签: javascript node.js azure azure-functions azure-application-insights


    【解决方案1】:

    你可以试试这行代码:

    //operation id
    var s = client.context.keys["operationId"];
    

    我是通过debug找到的,截图如下:

    【讨论】:

    • 在这种情况下,s 将包含“ai.operation.id” - 查找操作 id 值的键,在我的情况下,.context.tags["ai.operation.id"] 未定义:(
    • 通过client.context.tags[client.context.keys.operationId]等键值访问标签可能会有所帮助
    【解决方案2】:

    不确定 Azure Functions,但在节点 js 应用程序中我可以使用:

    const AppInsights = require("applicationinsights");
    var context = AppInsights.getCorrelationContext();
    var oid = context.operation.id;
    

    保证在模块版本 1.8.0 中工作

    【讨论】:

      【解决方案3】:

      阅读nodejs客户端中的文档,我认为您必须将setDistributedTracingMode设置为appInsights.DistributedTracingModes.AI

      这就是 operationId 正在做的事情,它有助于跟踪分布式系统,以便您可以关联请求。

      来自documentation page

      let appInsights = require("applicationinsights");
      appInsights.setup("<instrumentation_key>")
          .setDistributedTracingMode(appInsights.DistributedTracingModes.AI)
          .start();
      

      operationId 是 Application Insights SDK 在每个请求上自动添加的值,但显然是在稍后阶段,当您尝试访问它时还为时过早。这就是黑盒解决方案的问题。但是您可以尝试自己设置它。将 telemetry.context.operation.id 设置为您自己的唯一 ID,并确认 ApplicationInsights 是否正确跟踪。

      【讨论】:

      • 我已明确启用它,但它不起作用。我对如何访问 operationid 值的代码更感兴趣。
      • @UserControl operationId 是 Application Insights SDK 在每个请求上自动添加的值,但显然是在稍后阶段,当您尝试访问它时还为时过早。这就是黑盒解决方案的问题。尝试自己设置!将 telemetry.context.operation.id 设置为您自己的唯一 ID,并确认 ApplicationInsights 是否正确跟踪。
      • @UserControl 因为您使用的是 azure 函数应用程序我想这是操作的开始,所以它是 operation_id 自动生成的地方。如果您有一个 Web 应用程序,那么访问它会更容易。但是尝试上面的建议,它应该可以工作
      • @Stellios,我试过了,不幸的是它不起作用。
      • @UserControl 如果这不起作用,我就没有主意了。祝你好运!
      【解决方案4】:

      根据documentation,您可以通过调用context.executionContext.invocationId来访问或编辑操作ID。

      【讨论】:

        猜你喜欢
        • 2019-01-15
        • 1970-01-01
        • 2019-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-07
        • 2022-01-04
        • 1970-01-01
        相关资源
        最近更新 更多