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

在Node.js Express Azure WebApp中配置Azure AppInsights日志与异常追踪

为Node.js Express Azure WebApp配置Azure AppInsights的解决方案

一、修复异常未单独显示的问题

当前手动调用trackException却仍以trace类型记录,大概率是自动收集配置冲突或调用逻辑问题,可按以下步骤调整:

  1. 调整AppInsights初始化配置
    修改appInsights.js,关闭自动收集异常避免冲突,同时优化控制台收集规则:

    const appInsights = require('applicationinsights');
    
    appInsights.setup(process.env.APPLICATIONINSIGHTS_CONNECTION_STRING)
      .setAutoCollectConsole(true, false) // 第二个参数设为false,避免将console.error转为trace
      .setAutoCollectExceptions(false) // 关闭自动收集,改为全局中间件统一处理
      .start();
    
    module.exports = appInsights;
    
  2. 添加Express全局错误中间件统一捕获异常
    在Express主文件(如app.js)中新增全局错误中间件,覆盖所有路由的异常处理,确保异常以exception类型记录:

    const express = require('express');
    const app = express();
    const appInsights = require('./services/appInsights');
    const aiClient = appInsights.defaultClient;
    
    // 引入路由
    const indexRouter = require('./routes/index');
    app.use('/', indexRouter);
    
    // 全局错误处理中间件(必须放在所有路由之后)
    app.use((err, req, res, next) => {
      aiClient.trackException({
        exception: err,
        properties: {
          route: req.originalUrl,
          method: req.method
        }
      });
      console.error('全局捕获异常:', err);
      res.status(500).send('Internal Server Error');
    });
    

    同时修改路由中的catch逻辑,将错误传递给全局中间件处理:

    router.post('/api/messages', async function (req, res, next) {
      console.log("--inside /messages--")
      try {
        // 调用botService的方法
        await botService.someMethod();
        res.sendStatus(200);
      } catch (error) {
        console.error('Error in /messages:', error);
        // 传递错误到全局中间件
        next(error);
      }
    });
    

二、解决bot.js中重复日志的问题

Node.js模块是单例模式,重复导入不会重新初始化,重复日志是因为额外的初始化操作导致的。只需在bot.js中复用已初始化的客户端即可:

// bot.js
const appInsights = require('./services/appInsights');
const aiClient = appInsights.defaultClient;

function someMethod() {
  console.log("bot service method executed");
  // 可选:手动记录自定义trace(自动收集已开启console日志,此步骤可省略)
  aiClient.trackTrace({ 
    message: "bot service method executed", 
    severity: appInsights.Contracts.SeverityLevel.Information 
  });

  try {
    // 模拟业务逻辑异常
    throw new Error("Bot service internal error");
  } catch (err) {
    aiClient.trackException({ exception: err });
    throw err; // 抛出后由上层路由或全局中间件处理
  }
}

module.exports = { someMethod };

三、验证配置效果

  1. 部署更新后的代码到Azure WebApp
  2. 在Azure门户的App Insights中,通过日志模块验证:
    • 异常数据会出现在exceptions表中
    • 控制台日志会出现在traces表中
  3. 可使用Kusto查询快速验证:
    // 查询最近10条异常
    exceptions
    | order by timestamp desc
    | take 10
    
    // 查询最近10条trace日志
    traces
    | order by timestamp desc
    | take 10
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:15:54