我如何修复'模块未找到:将Azure Application Insight与Next.JS和OpenTelemetry一起使用时无法解决“os”错误?

kuhbmx9i  于 2023-06-05  发布在  其他
关注(0)|答案(1)|浏览(82)

希望将Next.js应用程序记录到Azure Application insight
我有以下instrumentation.ts代码

import { AzureMonitorTraceExporter } from '@azure/monitor-opentelemetry-exporter'
import { Resource } from '@opentelemetry/resources'
import {
  NodeTracerProvider,
  SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-node'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'

export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const provider = new NodeTracerProvider({
      resource: new Resource({
        [SemanticResourceAttributes.SERVICE_NAME]: 'my-app',
      }),
    })

    // Create an exporter instance
    const exporter = new AzureMonitorTraceExporter({
      connectionString:
        process.env['APPLICATIONINSIGHTS_CONNECTION_STRING'] ||
        '<your connection string>',
    })

    provider.addSpanProcessor(new SimpleSpanProcessor(exporter))
    provider.register()
  }
}

这会导致启动应用程序时出现以下错误
../../node_modules/@azure/monitor-opentelemetry-exporter/dist-esm/src/export/statsbeat/statsbeatMetrics.js:6:0 Module not found: Can't resolve 'os'
有什么好办法吗?

cwdobuhd

cwdobuhd1#

错误消息是由于缺少相关性。
这个@azure/monitor-opentelemetry-exporter包依赖于os模块,这是一个内置的Node.js模块。
os模块添加到您的项目依赖项中,并在终端中运行以下命令,您可以解决它。

npm install os

另一种方法是通过运行以下命令将@azure/monitor-opentelemetry-exporter包更新到最新版本。

npm install @azure/monitor-opentelemetry-exporter@latest

并查看official Azure documentation中的说明,以使用OpenTelemetry将Next.js应用程序记录到Azure Application Insights。
痕迹

跟踪日志:

查看日志跟踪的代码

import { TelemetryClient } from 'applicationinsights';
appInsights.trackEvent({ name: 'HelloWorldSuccess', properties: { message: 'Hello, World!' } });

throw new Error('Simulated error');

catch (error) 
{
   appInsights.trackException({ exception: error });
} 
finally {
   await appInsights.flush();
   console.log('Telemetry sent successfully.');
}

已将遥测放入此location

相关问题