You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Node.js的Azure Application Insights用户统计监控问题

如何在Node.js应用的Azure Application Insights中收集用户相关信息

1. 手动关联用户标识

基础配置仅收集请求元数据,要统计用户数量,需为每个请求绑定唯一用户ID。以Express框架为例,可通过中间件从请求中提取用户标识(如会话ID、登录用户ID或自定义请求头),并写入Application Insights上下文:

const appInsights = require("applicationinsights");
const express = require('express');
const app = express();

appInsights.setup(process.env.APPLICATIONINSIGHTS_CONNECTION_STRING).start();

// 中间件:绑定用户ID到遥测上下文
app.use((req, res, next) => {
  // 根据你的认证方式获取用户标识(示例从session或自定义头提取)
  const userId = req.session?.userId || req.headers['x-user-id'];
  
  if (userId) {
    // 将用户ID关联到所有后续遥测数据
    appInsights.defaultClient.context.tags[appInsights.defaultClient.context.keys.userId] = userId;
  }
  
  next();
});

// 业务路由示例
app.get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(3000);

设置完成后,Azure门户的用户面板会自动统计独立用户数、新用户数等核心指标。

2. 收集设备类型等客户端信息

设备类型、浏览器信息需从请求的User-Agent头解析,可借助useragent库处理:

  1. 安装依赖:
npm install useragent
  1. 添加中间件解析并上报设备信息:
const useragent = require('useragent');

app.use((req, res, next) => {
  const agent = useragent.parse(req.headers['user-agent']);
  const deviceType = agent.device.family; // 设备类型,如"iPhone"、"Windows Desktop"
  const browserInfo = agent.toAgent(); // 浏览器版本,如"Chrome 118.0.0.0"

  // 方式1:上报自定义事件,单独记录设备信息
  appInsights.defaultClient.trackEvent({
    name: 'UserDeviceInfo',
    properties: {
      userId: req.session?.userId,
      deviceType: deviceType,
      browser: browserInfo
    }
  });

  // 方式2:将设备类型绑定到全局上下文,让所有遥测携带该属性
  appInsights.defaultClient.context.tags['ai.user.deviceType'] = deviceType;
  
  next();
});

3. 查看统计数据

  • 进入Azure Application Insights资源的用户面板,可查看用户数、用户留存等指标。
  • 在自定义事件面板筛选UserDeviceInfo事件,可统计不同设备、浏览器的用户分布。
  • 也可通过日志查询(Kusto语言)深度分析,比如:
customEvents
| where name == "UserDeviceInfo"
| summarize userCount = dcount(properties.userId) by properties.deviceType

内容的提问来源于stack exchange,提问作者KANGO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:40:17