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

Node.js Azure Function使用appInsights v2.1.4调用setup().start()报错

问题原因
  • 初始化逻辑错误:appInsights.setup().start()是Application Insights的全局初始化方法,仅需要在应用启动时执行1次,你当前封装的日志类每次打info/error日志都会重复执行初始化,导致内部依赖的OpenTelemetry模块重复加载、实例状态混乱。
  • 依赖版本冲突:applicationinsights v2.1.4内置依赖的@opentelemetry/api版本和你项目中其他依赖引入的@opentelemetry/api版本不匹配,低版本的opentelemetry api没有createContextKey方法,触发类型错误。
解决方案

1. 修正Application Insights初始化逻辑

把初始化逻辑从日志方法里移到模块加载时执行,全局仅初始化一次,修改后的日志工具类代码如下:

const appInsights = require('applicationinsights');

// 全局仅初始化一次,加载时自动执行,会自动读取环境变量APPINSIGHTS_INSTRUMENTATIONKEY
appInsights.setup().start();
const client = appInsights.defaultClient;

class AppInsightsLog {
    error (context, eventName, error) {
        context.log.error(error);
        client.trackEvent({ name: `Catch error: ${eventName}`, properties: error });
    }

    info (context, eventName, extraInfo = null) {
        context.log.info(eventName);
        client.trackEvent({ name: `Log info: ${eventName}`, properties: extraInfo });
    }
}

module.exports = { AppInsightsLog };

2. 修复依赖版本冲突

  • 方案一:锁定兼容的opentelemetry api版本,在package.json中添加对应配置强制版本统一。
    如果你使用yarn,添加resolutions配置:
    "resolutions": {
      "@opentelemetry/api": "~1.3.0"
    }
    
    如果你使用npm,添加overrides配置:
    "overrides": {
      "@opentelemetry/api": "~1.3.0"
    }
    
    配置完成后删除node_modules和lock文件,重新执行npm install或者yarn install安装依赖即可。
  • 方案二:升级Application Insights SDK到最新稳定版,新版本已经修复了大量依赖冲突问题,直接执行npm install applicationinsights@latest升级即可。

3. 可选适配

如果是在Azure Function消费计划中运行,建议在函数入口文件顶部就执行Application Insights的初始化,避免冷启动时初始化延迟导致的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:18:04