在服务器端NodeJS Application Insights事件

时间:2018-06-08 17:09:19

标签: node.js azure azure-application-insights telemetry

我有一个NodeJS应用,我正在使用applicationinsights NodeJS包(this)。根据描述here的ApplicationInsights数据模型,它说该属性存在,但我无法找到关于如何在我发送的遥测事件中设置此属性的代码。

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

2 个答案:

答案 0 :(得分:3)

根据您的描述,我只找到了有关JavaScript的Setting the user context in an ITelemetryInitializerAuthenticated users的ASP.NET教程。

然后我检查了User.tsMicrosoft Application Insights SDK for JavaScript下的setAuthenticatedUserContext方法,并在TelemetryContext.ts下找到了相关的代码段,如下所示:

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";
...
  

但是我无法找到关于如何在我发送的遥测事件中设置此属性的代码。

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

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

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

答案 1 :(得分:0)

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

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合同的列表,请在此处查看:

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

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

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

  • applicationinsights v1.8.8