在服务器端 NodeJS Application Insights 事件中添加经过身份验证的用户 ID 信息

Adding authenticated user ID information in server-side NodeJS Application Insights events

我有一个 NodeJS 应用程序,我在其中使用 applicationinsights NodeJS 包(this). According to ApplicationInsights data model described here,它说 属性 存在,但我找不到代码关于如何在我发送的遥测事件中设置这个 属性。

任何描述如何执行此操作的片段都会有所帮助!

根据你的描述,我只找到了ASP.NET关于Setting the user context in an ITelemetryInitializer and Authenticated users的教程JavaScript。

然后我查看了User.ts of Microsoft Application Insights SDK for JavaScript and found the related code snippet under TelemetryContext.ts下的setAuthenticatedUserContext方法如下:

if (typeof userContext.authenticatedId === "string") {
      envelope.tags[tagKeys.userAuthUserId] = userContext.authenticatedId;
}

然后查看ContextTagKeys.ts,发现上下文标签如下:

this.sessionId = "ai.session.id";
this.userAccountId = "ai.user.accountId";
this.userId = "ai.user.id";
this.userAuthUserId = "ai.user.authUserId";
...

but I am not able to find a code snipped as to how to set this property in the telemetry event I'm sending.

对于 NodeJS SDK,上下文标签键在 ContextTagKeys.ts 下。根据您的要求,您可以利用以下代码片段:

appInsights.defaultClient.context.tags[appInsights.defaultClient.context.keys.userAuthUserId] ="xxxx";

对于Session id, Account id或其他上下文字段,您只需选择相关的上下文标签键即可。

以防万一有人还在为根据每个请求将用户信息添加到遥测事件而苦苦挣扎,这就是我所做的:

const appInsights = require("applicationinsights");

appInsights.setup().start()
appInsights.defaultClient.addTelemetryProcessor(
  (envelope, context) => {
    // context keys from the `ContextTagKeys` contract
    const contextKeys = {
      userId: "userId",
      sessionId: "sessionId",
    }
    const getContextKey = (key) => {
      return appInsights.defaultClient.context.keys[key]
    }
    const setContextKey = (key, value) => {
      envelope.tags[key] = value;
    }

    // custom context that I set on per-request basis
    const requestContext = appInsights.getCorrelationContext().requestContext
    const data = envelope.data.baseData;

    for (const [key, value] of Object.entries(requestContext)) {
      switch (key) {
        case "userId":
          setContextKey(
            getContextKey("userId"),  // ai.user.id
            value                     // bob@example.com
          )
          break
        case "sessionId":
          setContextKey(
            getContextKey("userId"),  // ai.session.id
            value                     // 507f191e810c19729de860ea
          )
          break
        default:
          // if it's a custom property that doesn't belong in the
          // `ContextTagKeys` contract, such as browser information, add
          // it as a custom property on the `envelope.data.baseData` object
          data.properties[key] = value
      }
    }

    return true
  }
)

然后,由于我使用的是 Express,因此我创建了一个中间件函数,用于在上下文对象上设置每个请求的信息:

const express = require('express')
const Bowser = require("bowser");

const app = express();

// ...

app.use((req, res, next) => {
  const session = req.session;
  const userAgent = req.get('User-Agent')

  const sessionId = session.id
  const userId = session.userId
  const browser = Bowser.getParser(userAgent) 

  const currentRequestContext = 
    appInsights.getCorrelationContext().requestContext || {}

  const nextRequestContext = {
    ...currentRequestContext,
    sessionId,      // 507f191e810c19729de860ea 
    userId,         // bob@example.com
    browser:        // custom property, e.g. Firefox 83
      browser.getBrowserName() + " " + browser.getBrowserVersion()
  }

  appInsights.getCorrelationContext().requestContext = nextRequestContext

  next()
})

要获取所有可用 ContextTagKeys 合约的列表,请查看此处:

  • ContextTagKeys.ts
  • ContextTagKeys.ts(客户端库)
    • 客户端库中的某些 ContextTagKeys 似乎也可以在服务器端库中设置,这就是我如何获得 client_Browser 属性使用浏览器信息
    • 填充 ai.device.browserVersion 后显示在 Azure 门户中

下面是文档中有关如何创建您自己的自定义遥测处理器的示例:

以下是 GitHub 上帮助我找到正确解决方案的问题:

最后,这是我使用的 applicationinsights 版本:

  • applicationinsights v1.8.8