# @azure/monitor-opentelemetry 中文文档

规范地址：https://npmcn.com/package/%40azure/monitor-opentelemetry/

版本：1\.21\.0
npm 元数据更新时间：2026-11-06T00:46:12.407Z
中文译文更新时间：2026-11-07T13:10:57.058Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40azure/monitor-opentelemetry
原文对照：https://npmcn.com/package/%40azure/monitor-opentelemetry/?lang=original
项目主页：https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/monitor/monitor-opentelemetry/README.md
源码仓库：https://github.com/Azure/azure-sdk-for-js

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：2.1 MB，502 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=22\.0\.0
- 运行依赖：31 个
- 首次发布：2023-05-01T12:44:29.801Z
- 最新版本发布：2026-11-06T00:46:12.214Z
- 近 30 天下载量：5599138（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：292（近 12 个月 44 个）

## 中文简介

Azure 监视器 OpenTeleometry (节点.js)

## 安装

```sh
npm install @azure/monitor-opentelemetry
```

也可以使用：`pnpm add @azure/monitor-opentelemetry`、`yarn add @azure/monitor-opentelemetry`、`bun add @azure/monitor-opentelemetry`

## README

# JavaScript 的 Azure 监视器打开遥测

[![npm version](https://badge.fury.io/js/%40azure%2Fmonitor-opentelemetry.svg)](https://badge.fury.io/js/%40azure%2Fmonitor-opentelemetry)

## 开始

### 安装软件包

`npm install @azure/monitor-opentelemetry`

### 目前得到支持的环境

-   [节点.js的LTS版本](https://github.com/nodejs/release#release-schedule)
    
-   [支持运行时间的 OpenTeleometry](https://github.com/open-telemetry/opentelemetry-js#supported-runtimes)
    

> _警告:_ 这个SDK只适用于Node.js环境. 使用 [应用程序透视 JavaScript SDK](https://github.com/microsoft/ApplicationInsights-JS) 用于网页和浏览器设置.

看我们的 [支助政策](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) 更多细节.

### 先决条件

-   一个 [Azure 订阅](https://azure.microsoft.com/free/)
-   一个 [应用程序 Insights 工作空间](https://learn.microsoft.com/azure/azure-monitor/app/app-insights-overview/)

### 启用 Azure 监视器打开遥测客户端

> _重要内容:_ `useAzureMonitor` 必须叫 _在此之前_ 进口其它东西。 如果先从其他图书馆导入,可能会造成遥测损失.

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

const options: AzureMonitorOpenTelemetryOptions = {
  azureMonitorExporterOptions: {
    connectionString:
      process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
  },
};
useAzureMonitor(options);
```

-   连接字符串可以通过 `APPLICATIONINSIGHTS_CONNECTION_STRING`。 。 。 .
-   批次跨度处理可以配置标准 OpenTelemetry 环境变量 `OTEL_BSP_MAX_QUEUE_SIZE`, (中文(简体) ), `OTEL_BSP_MAX_EXPORT_BATCH_SIZE`, (中文(简体) ), `OTEL_BSP_SCHEDULE_DELAY`,以及 `OTEL_BSP_EXPORT_TIMEOUT`。 。 。 .
-   采样器可以通过 OpenTeleometry env vars 设置 `OTEL_TRACES_SAMPLER` 财务报告和审定财务报表 `OTEL_TRACES_SAMPLER_ARG` (优于 `samplingRatio` 选项)。 支持的采样器值 : `microsoft.rate_limited`, (中文(简体) ), `microsoft.fixed_percentage`, (中文(简体) ), `always_on`, (中文(简体) ), `always_off`, (中文(简体) ), `trace_id_ratio`, (中文(简体) ), `parentbased_always_on`, (中文(简体) ), `parentbased_always_off`, (中文(简体) ), `parentbased_trace_id_ratio`用于 `microsoft.rate_limited`中,数值为每秒 `trace_id_ratio`/parent based, arg是 \[0, 1\] 中的一个概率. 当省略参数时,则适用默认值(费率限制已禁用;概率默认值为 1)。 请参看上游 OpenTeleometer 环境变量 spec 完整上下文 : [https://oponteleometry.io/docs/specs/otel/configulation/sdk-环境-可变性/](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/)。 。 。 .
-   用来使用 **固定百分比采样器** (而不是默认的有限采样器),也可以:
    -   设置环境变量 `OTEL_TRACES_SAMPLER=microsoft.fixed_percentage` 带有可选 `OTEL_TRACES_SAMPLER_ARG` 关于取样概率(例如, `0.5` 50%).
    -   设定 `tracesPerSecond: 0` 在 distro 选项中,该选项将禁用速率限制并返回使用 `samplingRatio` 固定百分比抽样.

### 无害环境管理支助

> _说明:_ 无害环境管理支持需要18.19.0节点或以后。 关于在OpenTeleometry中支持无害环境管理的更详细情况,参见: [开放远程计量无害环境管理 辅助文件](https://github.com/open-telemetry/opentelemetry-js/blob/main/doc/esm-support.md)。 。 。 .

对于ECMAScript模块(ESM)应用,OpenTelemetry仪器化需要加载器钩被注册 **在此之前** 任何有仪器的模块( 如 `http`已装入。 这是无害环境管理的一项基本要求 -- -- 模块装入后无法装入仪器.

使用 `--import` 确保加载器在节点.js进程一开始就注册的旗帜。 替换 `<your-app-entry-point>` 与您应用程序主文件的路径( 例如 ), `./dist/index.js`, (中文(简体) ), `./src/index.mjs`, (中文(简体) ), `./server.js`等 :

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

比如说,你 `package.json`数字 :

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

然后在您的申请条目文件中,拨打 `useAzureMonitor()` 来配置 SDK :

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

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

对于CommonJS应用程序,不需要额外的旗帜- 包被导入时加载器会自动注册.

## 配置

```ts
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);
```

| 选项 | 说明 | 默认 |
| --- | --- | --- |
| `azureMonitorExporterOptions` | Azure 监视器 OpenTelemoter 导出器配置 . [这里有更多信息](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/monitor/monitor-opentelemetry-exporter) |  |
| `samplingRatio` | 采样比必须在范围 \[0,1\] 取出一个值, 1 表示所有数据都会被采样,0 所有追踪数据都将被取出. 仅在 `tracesPerSecond` 设置为 0. | `1` |
| `tracesPerSecond` | 使用有速率限制的采样器进行每秒采样的最大痕迹数. 设定为 0 以禁用速率限制并使用固定百分比抽样 `samplingRatio` 换句话说. | `5` |
| `instrumentationOptions` | 仪器库配置. [这里有更多信息](https://npmcn.com/package/%40azure/monitor-opentelemetry/#readme-instrumentation-libraries) | 
```javascript

{
  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` | 允许配置 Web 仪器 . | 

        `{    enabled: false,    connectionString: ""  }`
        
      

 |
| `resource` | 开口遥测资源. [这里有更多信息](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-resources) |  |
| `enableLiveMetrics` | 启用/ 残疾活度量衡 . | `true` |
| `enableStandardMetrics` | 启用/ 残疾标准计量 . | `true` |
| `logRecordProcessors` | 日志处理器组向全球日志提供者注册. |  |
| `spanProcessors` | 向全球跟踪提供者注册的跨度处理器阵列 . |  |
| `views` | 向全球计数器提供者注册的参数视图矩阵 . |  |
| `enableTraceBasedSamplingForLogs` | 启用基于跟踪的日志采样 . | `false` |
| `enablePerformanceCounters` | 启用性能计数器 . | `true` |

可用配置文件设置选项 `applicationinsights.json` 位于 @azure/monitor-opetetemetry 包安装文件夹的根文件夹下, Ex: `node_modules/@azure/monitor-opentelemetry`。这些配置值将适用于所有 AzureMonitor OpenTelemetryClient 实例.

Live Metrics 也尊重 Azure 监视器 OneSettings `FEATURE_LIVE_METRICS` 设置. 远程禁用停止了QuickPulse的投票、收集和出版而不停止 一般的痕迹,日志,或者其他的度量. 远程重新启用恢复订阅投票. 设置 `enableLiveMetrics` 改为 `false` 在本地配置中总是禁用 Live Metrics, 无论远程设置如何。 缺少或无效的远程设置 状态;在第一个有效设置之前,应用本地配置.

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

自定义 JSON 文件可用 `APPLICATIONINSIGHTS_CONFIGURATION_FILE` 环境变量.

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

## 仪器库

以下OpenTeleometry仪器库作为Azure Monitor OpenTeleometry的一部分被包括在内.

**说明:** Azure SDK, Azure函数, MongoDB, MySQL, PostgreSQL, Redis, 和 Redis-4 仪器默认可以用于分布式跟踪. HTTP/HTTPS仪器也默认启用. 其它所有仪器默认被禁用,可以通过设置启用 `enabled: true` 在仪器选项中.

> _警告:_ 仪器库基于实验性的OpenTeleometry规范. 微软 _预览_ 支持承诺是确保以下库向Azure Monitor应用 Insights发送数据,但突破变化或实验映射有可能会屏蔽一些数据元素.

### 分布式追踪

-   [HTTP/HTTPS 软件](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http)
-   [蒙戈DB](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-mongodb)
-   [MySQL 数据](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-mysql)
-   [邮资](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-pg)
-   [重写](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-redis)
-   [红外线4](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-redis-4)
-   [阿苏雷SDK](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/instrumentation/opentelemetry-instrumentation-azure-sdk)
-   [Azure 函数](https://github.com/Azure/azure-functions-nodejs-opentelemetry)

### 计量

-   [HTTP/HTTPS 软件](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http)

### 日志

-   [邦扬](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-bunyan)
    
-   [温斯顿](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-winston)
    
-   [控制台](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-console) (默认损坏;启用方式 `instrumentationOptions: { console: { enabled: true } }`(中文(简体) )
    
    一旦启用, 一组 `console` 收集的方法由 `logSeverity` 数值 `console` 返回到 `APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL` 环境变量( e)`NONE`, (中文(简体) ), `ERROR`, (中文(简体) ), `WARN`, (中文(简体) ), `INFO`, (中文(简体) ), `DEBUG`, (中文(简体) ), `VERBOSE`, (中文(简体) ), `ALL`; 见 [自诊断](https://npmcn.com/package/%40azure/monitor-opentelemetry/#readme-self-diagnostics)当 `logSeverity` 未设置。 譬如说, `WARN` 仅收集 `console.warn` 财务报告和审定财务报表 `console.error`时 `NONE` 禁用收藏 `console` (和所有其他) 完全的日志.
    

其他开放的遥测仪器 [这里](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages) 并可以使用 AzureMonitor OpenTelemetricClient 中的 TracerProvider 添加.

```ts
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()],
});
```

### 应用程序 Insights 浏览器 SDK 加载器

应用程序 Insights 浏览器 SDK 加载器允许您在以下条件属实时将web SDK注入节点服务器响应:

-   反应有状态代码 `200`。 。 。 .
-   反应方法是 `GET`。 。 。 .
-   服务器响应有: `Conent-Type` html 标题.
-   服务器共振包含两个和标签.
-   响应中不包含当前/备份的网络仪器CDN端点. (当前和备份的网络仪器 CDN 端点) [这里](https://github.com/microsoft/ApplicationInsights-JS#active-public-cdn-endpoints)(中文(简体) )

关于浏览器SDK加载器使用情况的进一步信息可找到 [这里](https://learn.microsoft.com/azure/azure-monitor/app/javascript-sdk?tabs=javascriptwebsdkloaderscript)。 。 。 .

## 设置云角色名和云角色实例

您可以通过 : [打开远程资源](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/sdk.md#resource-sdk) 属性.

```ts
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);
```

资源标准属性信息参见: [资源语义公约](https://github.com/open-telemetry/semantic-conventions/tree/main/docs/resource)。 。 。 .

## 修改遥测

本节解释如何修改遥测.

### 添加跨度属性

要添加跨度属性,请使用以下两种方法:

-   使用由 [仪器库](https://npmcn.com/package/%40azure/monitor-opentelemetry/#readme-instrumentation-libraries)。 。 。 .
-   添加自定义跨度处理器 .

这些属性可能包括在您的遥测中添加自定义属性 .

> _提示 :_ 使用仪器库提供的选项的优点是,在可用时,整个上下文都是可用的. 因此,用户可以选择添加或过滤更多属性. 例如,HttpClient 仪器库中的丰富选项让用户可以访问 httpRequestMessage 本身. 他们可以从中选择任何内容,并将其作为属性来存储.

#### 添加自定义属性到 Track

任意 [属性](https://npmcn.com/package/%40azure/monitor-opentelemetry/#readme-add-span-attributes) 以自定义属性导出.

使用自定义处理器 :

```ts
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);
```

#### 将操作名称添加到跟踪和日志

使用自定义的跨度处理器和日志记录处理器,以便从请求中附加和关联操作名称到依赖和日志.

```ts
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);
```

### 过滤遥测

您可以使用下列方法过滤出遥测器 以免它离开您的应用程序 .

1.  排除许多 HTTP 仪器库提供的 URL 选项 .
    
    以下例子说明如何通过使用 [HTTP/HTTPS 仪器库](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http)数字 :
    
    ```ts
    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.  使用自定义处理器 。 您可以使用自定义的跨度处理器来排除某些跨度被导出 。 要标记不导出的时间段, 设置 `TraceFlag` 改为 `DEFAULT`。 。 。 . 使用添加 [自定义属性示例](https://npmcn.com/package/%40azure/monitor-opentelemetry/#readme-add-a-custom-property-to-a-trace),但替换以下代码行:
    
    ```ts
    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;
        }
      }
    }
    ```
    

## 自定义遥测

本节解释如何从您的应用程序中收集自定义遥测 .

### 添加自定义度量衡

您可能想要收集超过所收集的参数 [仪器库](https://npmcn.com/package/%40azure/monitor-opentelemetry/#readme-instrumentation-libraries)。 。 。 .

OpenTeleometry API提供6个公尺"仪器",以涵盖各种公尺假想,在Metrics Explorer中可视化公尺时需要选择正确的"分解类型". 在使用OpenTelemetery Metric API发送公分量时,以及在使用仪器库时,这一要求是真实的.

下表列出每个开口遥测计量仪器推荐的汇总类型.

| 开口遥测仪器 | Azure 监视器聚合类型 |
| --- | --- |
| 计数器 | 总计 |
| 同步计数器 | 总计 |
| 直方图 | 平均, Sum, 计数( Max, Min for Python and Node.js 仅限) |
| 同步高地 | 平均数 |
| UpDownCounter(仅限Python和Node.js) 互联网档案馆的存檔,存档日期2013-12-02 | 总计 |
| 同步 UpDownCounter (仅限 Python 和 Node.js) | 总计 |

> > _注意:_ 超过表格显示的聚合类型通常没有意义.

这个 [OpenTeleometry 规格](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument) 描述仪器,并举例说明您何时可以使用每个仪器.

```ts
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" });
```

### 添加自定义例外

选择仪器库会自动支持应用程序 Insights 的例外. 然而,您可能想要手动报告非仪器库报告的例外. 举例来说,你的代码所发现的例外 _没有_ 通常不报告,你不妨报告 ,从而在相关经验中提请注意它们,包括故障刃和端到端的交易视图.

```ts
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);
}
```

## 解决问题

### 自诊断

Azure Monitor OpenTeleometry使用OpenTeleometry API Logger进行内部日志. 要启用,请使用以下代码:

```ts
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` 环境变量可用于设定理想的日志级别,支持以下数值: `NONE`, (中文(简体) ), `ERROR`, (中文(简体) ), `WARN`, (中文(简体) ), `INFO`, (中文(简体) ), `DEBUG`, (中文(简体) ), `VERBOSE` 财务报告和审定财务报表 `ALL`。 。 。 .

日志可以使用 `APPLICATIONINSIGHTS_LOG_DESTINATION` 环境变量, 支持值为 `file` 财务报告和审定财务报表 `file+console`,一个名为 `applicationinsights.log` 默认将在 tmp 文件夹中生成,包括所有日志, `/tmp` \*无 `USERDIR/AppData/Local/Temp` 用于 Windows 。 可用 `APPLICATIONINSIGHTS_LOGDIR` 环境变量.

## 实例

关于几个冠军方案的全部样本,见 [`samples/`](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/monitor/monitor-opentelemetry/samples-dev/) 文件夹.

## 关键概念

关于OpenTeleometry项目的更多信息,请审查 [**OpenTeleometry 规格**](https://github.com/open-telemetry/opentelemetry-specification#opentelemetry-specification)。 。 。 .

### 插件登记

要了解您是否已经为正在使用的库设置了插件, 请检查 [OpenTeleometry 注册](https://opentelemetry.io/registry/)。 。 。 .

如果您无法在注册库中创建您的库, 请随意建议一个新的插件请求 [`opentelemetry-js-contrib`](https://github.com/open-telemetry/opentelemetry-js-contrib)。 。 。 .

## 捐款

如果您想为图书馆捐钱 请读一下 [贡献指南](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) 学习如何构建和测试密码.

## 常见问题

### @azure/monitor-opentelemetry 是什么？

Azure 监视器 OpenTeleometry \(节点\.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 和提交记录判断。

