Just in case someone is still struggling with adding user information to the telemetry event on a per-request basis, here's what I did:
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 // [email protected]
)
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
}
)
Then, since I am using Express
, I created a middleware function that sets per-request information on the context object:
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, // [email protected]
browser: // custom property, e.g. Firefox 83
browser.getBrowserName() + " " + browser.getBrowserVersion()
}
appInsights.getCorrelationContext().requestContext = nextRequestContext
next()
})
To get a list of all available ContextTagKeys
contracts, have a look here:
- ContextTagKeys.ts
- ContextTagKeys.ts (client-side library)
- It appears that some of these
ContextTagKeys
from the client-side library can be set in the server-side library as well, which is how I got the client_Browser
property to show up in Azure portal after populating ai.device.browserVersion
with browser information
Here's an example from the documentation on how to create your own custom telemetry processor:
Here are the issues on GitHub that helped me find the proper solution:
Lastly, here's the version of applicationinsights
that I am using:
applicationinsights v1.8.8