@azure/monitor-opentelemetry

中文文档
1.21.0发布于 2026/11/06MITTypeScriptESM + CJS近 30 天下载 559.9万

Azure Monitor OpenTelemetry (Node.js)

原始使用文档
文档目录25 节
  1. Getting started
  2. Install the package
  3. Currently supported environments
  4. Prerequisites
  5. Enable Azure Monitor OpenTelemetry Client
  6. ESM Support
  7. Configuration
  8. Instrumentation libraries
  9. Distributed Tracing
  10. Metrics
  11. Logs
  12. Application Insights Browser SDK Loader
  13. Set the Cloud Role Name and the Cloud Role Instance
  14. Modify telemetry
  15. Add span attributes
  16. Filter telemetry
  17. Custom telemetry
  18. Add Custom Metrics
  19. Add Custom Exceptions
  20. Troubleshooting
  21. Self-diagnostics
  22. Examples
  23. Key concepts
  24. Plugin Registry
  25. Contributing

Azure Monitor OpenTelemetry for JavaScript

npm version

Getting started

Install the package

npm install @azure/monitor-opentelemetry

Currently supported environments

Warning: This SDK only works for Node.js environments. Use the Application Insights JavaScript SDK for web and browser scenarios.

See our support policy for more details.

Prerequisites

Enable Azure Monitor OpenTelemetry Client

Important: useAzureMonitor must be called before you import anything else. There may be resulting telemetry loss if other libraries are imported first.

import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";

const options: AzureMonitorOpenTelemetryOptions = {
  azureMonitorExporterOptions: {
    connectionString:
      process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
  },
};
useAzureMonitor(options);
  • Connection String can be set via APPLICATIONINSIGHTS_CONNECTION_STRING.
  • Batch span processing can be configured with the standard OpenTelemetry environment variables OTEL_BSP_MAX_QUEUE_SIZE, OTEL_BSP_MAX_EXPORT_BATCH_SIZE, OTEL_BSP_SCHEDULE_DELAY, and OTEL_BSP_EXPORT_TIMEOUT.
  • Sampler can be set via the OpenTelemetry env vars OTEL_TRACES_SAMPLER and OTEL_TRACES_SAMPLER_ARG (takes precedence over the samplingRatio option). Supported sampler values: microsoft.rate_limited, microsoft.fixed_percentage, always_on, always_off, trace_id_ratio, parentbased_always_on, parentbased_always_off, parentbased_trace_id_ratio. For microsoft.rate_limited, the arg is spans per second; for trace_id_ratio/parentbased, the arg is a probability in [0,1]. When the arg is omitted, defaults apply (rate limit disabled; probability defaults to 1). See the upstream OpenTelemetry environment variable spec for full context: https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/.
  • To use the fixed percentage sampler (instead of the default rate-limited sampler), you can either:
    • Set the environment variable OTEL_TRACES_SAMPLER=microsoft.fixed_percentage with an optional OTEL_TRACES_SAMPLER_ARG for the sampling probability (e.g., 0.5 for 50%).
    • Set tracesPerSecond: 0 in the distro options, which disables rate limiting and falls back to using samplingRatio for fixed percentage sampling.

ESM Support

Note: ESM support requires Node.js 18.19.0 or later. For more details on ESM support in OpenTelemetry, see the OpenTelemetry ESM Support documentation.

For ECMAScript Module (ESM) applications, OpenTelemetry instrumentation requires the loader hooks to be registered before any instrumented modules (like http) are loaded. This is a fundamental requirement of ESM - modules cannot be instrumented after they are loaded.

Use the --import flag to ensure the loader is registered at the very start of the Node.js process. Replace <your-app-entry-point> with the path to your application's main file (e.g., ./dist/index.js, ./src/index.mjs, ./server.js, etc.):

node --import @azure/monitor-opentelemetry/loader <your-app-entry-point>

For example, in your package.json:

{
  "scripts": {
    "start": "node --import @azure/monitor-opentelemetry/loader ./dist/index.js"
  }
}

Then in your application entry file, call useAzureMonitor() to configure the SDK:

import { useAzureMonitor } from "@azure/monitor-opentelemetry";

useAzureMonitor({
  azureMonitorExporterOptions: {
    connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,
  },
});

For CommonJS applications, no additional flags are needed - the loader is automatically registered when the package is imported.

Configuration

import { resourceFromAttributes } from "@opentelemetry/resources";
import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";
import { SeverityNumber } from "@opentelemetry/api-logs";

const resource = resourceFromAttributes({ testAttribute: "testValue" });
const options: AzureMonitorOpenTelemetryOptions = {
  azureMonitorExporterOptions: {
    // Offline storage
    storageDirectory: "c://azureMonitor",
    // Automatic retries
    disableOfflineStorage: false,
    // Application Insights Connection String
    connectionString:
      process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
  },
  samplingRatio: 1,
  instrumentationOptions: {
    // Instrumentations generating traces
    azureSdk: { enabled: true },
    http: { enabled: true },
    mongoDb: { enabled: true },
    mySql: { enabled: true },
    postgreSql: { enabled: true },
    redis: { enabled: true },
    redis4: { enabled: true },
    // Instrumentations generating logs
    bunyan: { enabled: true },
    winston: { enabled: true },
    // Console log collection is opt-in (disabled by default).
    // `logSeverity` takes precedence over the
    // APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL environment variable.
    console: { enabled: false, logSeverity: SeverityNumber.WARN },
  },
  enableLiveMetrics: true,
  enableStandardMetrics: true,
  browserSdkLoaderOptions: {
    enabled: false,
    connectionString: "",
  },
  resource: resource,
  logRecordProcessors: [],
  spanProcessors: [],
  views: [],
};
useAzureMonitor(options);
Option Description Default
azureMonitorExporterOptions Azure Monitor OpenTelemetry Exporter Configuration. More info here
samplingRatio Sampling ratio must take a value in the range [0,1], 1 meaning all data will sampled and 0 all Tracing data will be sampled out. Only used when tracesPerSecond is set to 0. 1
tracesPerSecond The maximum number of traces to sample per second using the rate-limited sampler. Set to 0 to disable rate limiting and use fixed percentage sampling with samplingRatio instead. 5
instrumentationOptions Instrumentation libraries configuration. More info here

{
  http: { enabled: true },
  azureSdk: { enabled: true },
  mongoDb: { enabled: true },
  mySql: { enabled: true },
  postgreSql: { enabled: true },
  redis: { enabled: true },
  redis4: { enabled: true },
  bunyan: { enabled: false }, 
  winston: { enabled: false }, 
  console: { enabled: false } 
}
      
browserSdkLoaderOptions Allow configuration of Web Instrumentations.
        
{ 
  enabled: false, 
  connectionString: "" 
}
        
      
resource Opentelemetry Resource. More info here
enableLiveMetrics Enable/Disable Live Metrics. true
enableStandardMetrics Enable/Disable Standard Metrics. true
logRecordProcessors Array of log record processors to register to the global logger provider.
spanProcessors Array of span processors to register to the global tracer provider.
views Array of metric views to register to the global meter provider.
enableTraceBasedSamplingForLogs Enable log sampling based on trace. false
enablePerformanceCounters Enable performance counters. true

Options could be set using configuration file applicationinsights.json located under root folder of @azure/monitor-opentelemetry package installation folder, Ex: node_modules/@azure/monitor-opentelemetry. These configuration values will be applied to all AzureMonitorOpenTelemetryClient instances.

Live Metrics also honors the Azure Monitor OneSettings FEATURE_LIVE_METRICS setting. Remote disablement stops QuickPulse polling, collection, and publishing without stopping ordinary traces, logs, or other metrics. Remote re-enablement resumes subscription polling. Setting enableLiveMetrics to false in the local configuration always disables Live Metrics, regardless of the remote setting. Missing or invalid remote settings preserve the last valid state; before the first valid setting, the local configuration applies.

{
    "samplingRatio": 0.8,
    "enableStandardMetrics": true,
    "enableLiveMetrics": true,
    "instrumentationOptions":{
        "azureSdk": {
            "enabled": false
        }
    },
    ...
}

Custom JSON file could be provided using APPLICATIONINSIGHTS_CONFIGURATION_FILE environment variable.

process.env["APPLICATIONINSIGHTS_CONFIGURATION_FILE"] = "path/to/customConfig.json";

Instrumentation libraries

The following OpenTelemetry Instrumentation libraries are included as part of Azure Monitor OpenTelemetry.

Note: The Azure SDK, Azure Functions, MongoDB, MySQL, PostgreSQL, Redis, and Redis-4 instrumentations are enabled by default for distributed tracing. The HTTP/HTTPS instrumentation is also enabled by default. All other instrumentations are disabled by default and can be enabled by setting enabled: true in the instrumentation options.

Warning: Instrumentation libraries are based on experimental OpenTelemetry specifications. Microsoft's preview support commitment is to ensure that the following libraries emit data to Azure Monitor Application Insights, but it's possible that breaking changes or experimental mapping will block some data elements.

Distributed Tracing

Metrics

Logs

  • Bunyan

  • Winston

  • Console (disabled by default; enable with instrumentationOptions: { console: { enabled: true } })

    Once enabled, the set of console methods collected is filtered by the logSeverity value on the console instrumentation options, falling back to the APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL environment variable (NONE, ERROR, WARN, INFO, DEBUG, VERBOSE, ALL; see Self-diagnostics) when logSeverity is not set. For example, WARN collects only console.warn and console.error, while NONE disables collection of console (and all other) logs entirely.

Other OpenTelemetry Instrumentations are available here and could be added using TracerProvider in AzureMonitorOpenTelemetryClient.

import { useAzureMonitor } from "@azure/monitor-opentelemetry";
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { trace, metrics } from "@opentelemetry/api";
import { ExpressInstrumentation } from "@opentelemetry/instrumentation-express";

useAzureMonitor();
registerInstrumentations({
  tracerProvider: trace.getTracerProvider(),
  meterProvider: metrics.getMeterProvider(),
  instrumentations: [new ExpressInstrumentation()],
});

Application Insights Browser SDK Loader

Application Insights Browser SDK Loader allows you to inject the web SDK into node server responses when the following conditions are true:

  • Response has status code 200.
  • Response method is GET.
  • Server response has the Conent-Type html header.
  • Server resonse contains both and tags.
  • Response does not contain current /backup web Instrumentation CDN endpoints. (current and backup Web Instrumentation CDN endpoints here)

Further information on usage of the browser SDK loader can be found here.

Set the Cloud Role Name and the Cloud Role Instance

You might set the Cloud Role Name and the Cloud Role Instance via OpenTelemetry Resource attributes.

import { emptyResource } from "@opentelemetry/resources";
import {
  ATTR_SERVICE_NAME,
  SEMRESATTRS_SERVICE_NAMESPACE,
  SEMRESATTRS_SERVICE_INSTANCE_ID,
} from "@opentelemetry/semantic-conventions";
import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";

// ----------------------------------------
// Setting role name and role instance
// ----------------------------------------
const customResource = emptyResource();
customResource.attributes[ATTR_SERVICE_NAME] = "my-helloworld-service";
customResource.attributes[SEMRESATTRS_SERVICE_NAMESPACE] = "my-namespace";
customResource.attributes[SEMRESATTRS_SERVICE_INSTANCE_ID] = "my-instance";

const options: AzureMonitorOpenTelemetryOptions = { resource: customResource };
useAzureMonitor(options);

For information on standard attributes for resources, see Resource Semantic Conventions.

Modify telemetry

This section explains how to modify telemetry.

Add span attributes

To add span attributes, use either of the following two ways:

These attributes might include adding a custom property to your telemetry.

Tip: The advantage of using options provided by instrumentation libraries, when they're available, is that the entire context is available. As a result, users can select to add or filter more attributes. For example, the enrich option in the HttpClient instrumentation library gives users access to the httpRequestMessage itself. They can select anything from it and store it as an attribute.

Add a custom property to a Trace

Any attributes you add to spans are exported as custom properties.

Use a custom processor:

import { SpanProcessor, ReadableSpan } from "@opentelemetry/sdk-trace-base";
import { Span } from "@opentelemetry/api";
import { SEMATTRS_HTTP_CLIENT_IP } from "@opentelemetry/semantic-conventions";
import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";

class SpanEnrichingProcessor implements SpanProcessor {
  async forceFlush(): Promise<void> {
    // Flush code here
  }
  async shutdown(): Promise<void> {
    // shutdown code here
  }
  onStart(_span: Span): void {}
  onEnd(span: ReadableSpan): void {
    span.attributes["CustomDimension1"] = "value1";
    span.attributes["CustomDimension2"] = "value2";
    span.attributes[SEMATTRS_HTTP_CLIENT_IP] = "<IP Address>";
  }
}

// Enable Azure Monitor integration.
const options: AzureMonitorOpenTelemetryOptions = {
  // Add the SpanEnrichingProcessor
  spanProcessors: [new SpanEnrichingProcessor()],
};

useAzureMonitor(options);

Add Operation Name to Traces and Logs

Use a custom span processor and log record processor in order to attach and correlate operation name from requests to dependencies and logs.

import { SpanProcessor, ReadableSpan } from "@opentelemetry/sdk-trace-base";
import { Span, Context, trace } from "@opentelemetry/api";
import { AI_OPERATION_NAME } from "@azure/monitor-opentelemetry-exporter";
import { LogRecordProcessor, SdkLogRecord } from "@opentelemetry/sdk-logs";
import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";

class SpanEnrichingProcessor implements SpanProcessor {
  async forceFlush(): Promise<void> {
    // Flush code here
  }
  async shutdown(): Promise<void> {
    // shutdown code here
  }
  onStart(_span: Span, _context: Context): void {
    const parentSpan = trace.getSpan(_context);
    if (parentSpan && "name" in parentSpan) {
      // If the parent span has a name we can assume it is a ReadableSpan and cast it.
      _span.setAttribute(AI_OPERATION_NAME, (parentSpan as unknown as ReadableSpan).name);
    }
  }
  onEnd(_span: ReadableSpan): void {}
}

class LogRecordEnrichingProcessor implements LogRecordProcessor {
  async forceFlush(): Promise<void> {
    // Flush code here
  }
  async shutdown(): Promise<void> {
    // shutdown code here
  }
  onEmit(_logRecord: SdkLogRecord, _context: Context): void {
    const parentSpan = trace.getSpan(_context);
    if (parentSpan && "name" in parentSpan) {
      // If the parent span has a name we can assume it is a ReadableSpan and cast it.
      _logRecord.setAttribute(AI_OPERATION_NAME, (parentSpan as unknown as ReadableSpan).name);
    }
  }
}

// Enable Azure Monitor integration.
const options: AzureMonitorOpenTelemetryOptions = {
  // Add the SpanEnrichingProcessor
  spanProcessors: [new SpanEnrichingProcessor()],
  logRecordProcessors: [new LogRecordEnrichingProcessor()],
};

useAzureMonitor(options);

Filter telemetry

You might use the following ways to filter out telemetry before it leaves your application.

  1. Exclude the URL option provided by many HTTP instrumentation libraries.

    The following example shows how to exclude a certain URL from being tracked by using the HTTP/HTTPS instrumentation library:

    import { HttpInstrumentationConfig } from "@opentelemetry/instrumentation-http";
    import { IncomingMessage, RequestOptions } from "node:http";
    import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";
    
    const httpInstrumentationConfig: HttpInstrumentationConfig = {
      enabled: true,
      ignoreIncomingRequestHook: (request: IncomingMessage) => {
        // Ignore OPTIONS incoming requests
        if (request.method === "OPTIONS") {
          return true;
        }
        return false;
      },
      ignoreOutgoingRequestHook: (options: RequestOptions) => {
        // Ignore outgoing requests with /test path
        if (options.path === "/test") {
          return true;
        }
        return false;
      },
    };
    
    const options: AzureMonitorOpenTelemetryOptions = {
      instrumentationOptions: {
        http: httpInstrumentationConfig,
      },
    };
    
    useAzureMonitor(options);
    
  2. Use a custom processor. You can use a custom span processor to exclude certain spans from being exported. To mark spans to not be exported, set TraceFlag to DEFAULT. Use the add custom property example, but replace the following lines of code:

    import { SpanProcessor, ReadableSpan } from "@opentelemetry/sdk-trace-base";
    import { Span, Context, SpanKind, TraceFlags } from "@opentelemetry/api";
    
    class SpanEnrichingProcessor implements SpanProcessor {
      async forceFlush(): Promise<void> {
        // Force flush code here
      }
      onStart(_span: Span, _parentContext: Context): void {
        // Normal code here
      }
      async shutdown(): Promise<void> {
        // Shutdown code here
      }
      onEnd(span: ReadableSpan): void {
        if (span.kind === SpanKind.INTERNAL) {
          span.spanContext().traceFlags = TraceFlags.NONE;
        }
      }
    }
    

Custom telemetry

This section explains how to collect custom telemetry from your application.

Add Custom Metrics

You may want to collect metrics beyond what is collected by instrumentation libraries.

The OpenTelemetry API offers six metric "instruments" to cover a variety of metric scenarios and you'll need to pick the correct "Aggregation Type" when visualizing metrics in Metrics Explorer. This requirement is true when using the OpenTelemetry Metric API to send metrics and when using an instrumentation library.

The following table shows the recommended aggregation types for each of the OpenTelemetry Metric Instruments.

OpenTelemetry InstrumentAzure Monitor Aggregation Type
CounterSum
Asynchronous CounterSum
HistogramAverage, Sum, Count (Max, Min for Python and Node.js only)
Asynchronous GaugeAverage
UpDownCounter (Python and Node.js only)Sum
Asynchronous UpDownCounter (Python and Node.js only)Sum

Caution: Aggregation types beyond what's shown in the table typically aren't meaningful.

The OpenTelemetry Specification describes the instruments and provides examples of when you might use each one.

import { useAzureMonitor } from "@azure/monitor-opentelemetry";
import { metrics, ObservableResult } from "@opentelemetry/api";

useAzureMonitor();
const meter = metrics.getMeter("testMeter");

const histogram = meter.createHistogram("histogram");
const counter = meter.createCounter("counter");
const gauge = meter.createObservableGauge("gauge");
gauge.addCallback((observableResult: ObservableResult) => {
  const randomNumber = Math.floor(Math.random() * 100);
  observableResult.observe(randomNumber, { testKey: "testValue" });
});

histogram.record(1, { testKey: "testValue" });
histogram.record(30, { testKey: "testValue2" });
histogram.record(100, { testKey2: "testValue" });

counter.add(1, { testKey: "testValue" });
counter.add(5, { testKey2: "testValue" });
counter.add(3, { testKey: "testValue2" });

Add Custom Exceptions

Select instrumentation libraries automatically support exceptions to Application Insights. However, you may want to manually report exceptions beyond what instrumention libraries report. For instance, exceptions caught by your code are not ordinarily not reported, and you may wish to report them and thus draw attention to them in relevant experiences including the failures blade and end-to-end transaction view.

import { useAzureMonitor } from "@azure/monitor-opentelemetry";
import { trace, Exception } from "@opentelemetry/api";

useAzureMonitor();
const tracer = trace.getTracer("testMeter");

const span = tracer.startSpan("hello");
try {
  throw new Error("Test Error");
} catch (error) {
  span.recordException(error as Exception);
}

Troubleshooting

Self-diagnostics

Azure Monitor OpenTelemetry uses the OpenTelemetry API Logger for internal logs. To enable it, use the following code:

import { useAzureMonitor } from "@azure/monitor-opentelemetry";

process.env["APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL"] = "VERBOSE";
process.env["APPLICATIONINSIGHTS_LOG_DESTINATION"] = "file";
process.env["APPLICATIONINSIGHTS_LOGDIR"] = "path/to/logs";

useAzureMonitor();

APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL environment variable could be used to set desired log level, supporting the following values: NONE, ERROR, WARN, INFO, DEBUG, VERBOSE and ALL.

Logs could be put into local file using APPLICATIONINSIGHTS_LOG_DESTINATION environment variable, supported values are file and file+console, a file named applicationinsights.log will be generated on tmp folder by default, including all logs, /tmp for *nix and USERDIR/AppData/Local/Temp for Windows. Log directory could be configured using APPLICATIONINSIGHTS_LOGDIR environment variable.

Examples

For complete samples of a few champion scenarios, see the samples/ folder.

Key concepts

For more information on the OpenTelemetry project, please review the OpenTelemetry Specifications.

Plugin Registry

To see if a plugin has already been made for a library you are using, please check out the OpenTelemetry Registry.

If you cannot your library in the registry, feel free to suggest a new plugin request at opentelemetry-js-contrib.

Contributing

If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.

版本与发布记录

@azure/monitor-opentelemetry 共发布 292 个版本,首次发布于 2023/05/01;过去 12 个月发布了 44 个版本。

版本发布日期距今
1.21.0latest2026/11/061 天前
1.20.12026/10/071 个月前
1.20.02026/09/052 个月前
1.19.02026/07/303 个月前
1.18.22026/07/024 个月前
1.18.12026/05/305 个月前

其他发布通道:dev → 1.16.0-alpha.20260311.1。

关于 @azure/monitor-opentelemetry 的常见问题

@azure/monitor-opentelemetry 是什么?

Azure Monitor OpenTelemetry (Node.js)

如何安装 @azure/monitor-opentelemetry?

在项目目录运行 npm install @azure/monitor-opentelemetry,或使用 pnpm add / yarn add / bun add。

@azure/monitor-opentelemetry 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@azure/monitor-opentelemetry 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@azure/monitor-opentelemetry 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@azure/monitor-opentelemetry 可以商用吗?

@azure/monitor-opentelemetry 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@azure/monitor-opentelemetry 的下载量有多少?

根据 npm 官方下载统计,@azure/monitor-opentelemetry 在 2026/10/08 – 2026/11/06 这 30 天内被下载 5,599,138 次,日均约 186,638 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@azure/monitor-opentelemetry 还在维护吗?

最新版本 1.21.0 发布于 2026/11/06(1 天前);至今共发布 292 个版本,其中过去 12 个月发布了 44 个;首次发布于 2023/05/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。