你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 JavaScript 的 Azure Monitor OpenTelemetry

npm 版本

入门

安装包

npm install @azure/monitor-opentelemetry

目前支持的环境

警告: 此 SDK 仅适用于 Node.js 环境。 使用 Application Insights JavaScript SDK 处理 Web 和浏览器方案。

有关更多详细信息,请参阅我们的支持政策

先决条件

启用 Azure Monitor OpenTelemetry 客户端

重要:useAzureMonitor 在导入任何其他内容 之前 ,必须调用 。 如果首先导入其他库,可能会导致遥测丢失。

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

const options: AzureMonitorOpenTelemetryOptions = {
  azureMonitorExporterOptions: {
    connectionString:
      process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
  },
}
useAzureMonitor(options);
  • 可以使用环境变量APPLICATIONINSIGHTS_CONNECTION_STRING设置连接字符串

配置

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

const resource = new Resource({ "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 },
    },
    enableLiveMetrics: true,
    enableStandardMetrics: true,
    browserSdkLoaderOptions: {
        enabled: false,
        connectionString: "",
    },
    resource: resource,
    logRecordProcessors: [],
    spanProcessors: []
};

useAzureMonitor(options);
属性 说明 默认
azureMonitorExporterOptions Azure Monitor OpenTelemetry 导出程序配置。 在此处了解详细信息
samplingRatio 采样比率必须采用 [0,1] 范围内的值,1 表示将采样所有数据,0 所有跟踪数据将被采样。 1
instrumentationOptions 允许配置 OpenTelemetry Instrumentations。 {“http”: { enabled: true },“azureSdk”: { enabled: false },“mongoDb”: { enabled: false },“mySql”: { enabled: false },“postgreSql”: { enabled: false },“redis”: { enabled: false },“bunyan”: { enabled: false }, “winston”: { enabled: false }
browserSdkLoaderOptions 允许配置 Web 检测。 { enabled: false, connectionString: “” }
resource Opentelemetry 资源。 在此处了解详细信息
samplingRatio 采样比率必须采用 [0,1] 范围内的值,1 表示将采样所有数据,0 所有跟踪数据将被采样。 1
enableLiveMetrics 启用/禁用实时指标。 false
enableStandardMetrics 启用/禁用标准指标。 true
logRecordProcessors 要注册到全局记录器提供程序的日志记录处理器数组。
spanProcessors 要注册到全局跟踪器提供程序的跨度处理器数组。

可以使用位于包安装文件夹的根文件夹下的配置文件applicationinsights.json来设置选项,例如: node_modules/@azure/monitor-opentelemetry。@azure/monitor-opentelemetry 这些配置值将应用于所有 AzureMonitorOpenTelemetryClient 实例。

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

可以使用环境变量提供 APPLICATIONINSIGHTS_CONFIGURATION_FILE 自定义 JSON 文件。

process.env.APPLICATIONINSIGHTS_CONFIGURATION_FILE = "C:/applicationinsights/config/customConfig.json"

// Application Insights SDK setup....

检测库

以下 OpenTelemetry Instrumentation 库作为 Azure Monitor OpenTelemetry 的一部分包含在内。

警告: 检测库基于实验性 OpenTelemetry 规范。 Microsoft 的预览版支持承诺是为了确保以下库向 Azure Monitor Application Insights 发出数据,但中断性变更或实验性映射可能会阻止某些数据元素。

分布式跟踪

指标

日志

此处提供了其他 OpenTelemetry Instrumentations,可以使用 AzureMonitorOpenTelemetryClient 中的 TracerProvider 添加。

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

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

Application Insights 浏览器 SDK 加载程序

Application Insights 浏览器 SDK 加载程序允许在满足以下条件时将 Web SDK 注入节点服务器响应:

  • 响应的状态代码为 200
  • 响应方法为 GET
  • 服务器响应具有 Conent-Type html 标头。
  • 服务器共鸣同时包含 和 标记。
  • 响应不包含当前的 /backup Web 检测 CDN 终结点。 (此处为当前和备份 Web 检测 CDN 终结点)

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

可以通过 OpenTelemetry 资源 属性设置云角色名称和云角色实例。

import { useAzureMonitor, AzureMonitorOpenTelemetryOptions } from "@azure/monitor-opentelemetry";
import { Resource } from "@opentelemetry/resources";
import { SemanticResourceAttributes } from "@opentelemetry/semantic-conventions";

// ----------------------------------------
// Setting role name and role instance
// ----------------------------------------
const customResource = Resource.EMPTY;
customResource.attributes[SemanticResourceAttributes.SERVICE_NAME] = "my-helloworld-service";
customResource.attributes[SemanticResourceAttributes.SERVICE_NAMESPACE] = "my-namespace";
customResource.attributes[SemanticResourceAttributes.SERVICE_INSTANCE_ID] = "my-instance";

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

有关资源的标准属性的信息,请参阅资源语义约定

修改遥测

本部分介绍如何修改遥测。

添加范围属性

若要添加范围属性,请使用以下两种方法之一:

  • 使用检测库提供的选项。
  • 添加自定义范围处理器。

这些属性可能包括向遥测添加自定义属性。

提示: 使用检测库提供的选项(如果可用)的优点是整个上下文都可用。 因此,用户可以选择添加或筛选更多属性。 例如,HttpClient 检测库中的扩充选项让用户可以访问 httpRequestMessage。 他们可以从中选择任何内容并将其存储为属性。

将自定义属性添加到跟踪

你添加到范围的任何属性都将导出为自定义属性。

使用自定义处理器:

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


class SpanEnrichingProcessor implements SpanProcessor{
  forceFlush(): Promise<void>{
    return Promise.resolve();
  }
  shutdown(): Promise<void>{
    return Promise.resolve();
  }
  onStart(_span: Span): void{}
  onEnd(span: ReadableSpan){
    span.attributes["CustomDimension1"] = "value1";
    span.attributes["CustomDimension2"] = "value2";
    span.attributes[SemanticAttributes.HTTP_CLIENT_IP] = "<IP Address>";
  }
}

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

筛选遥测数据

可以使用以下方法,在遥测数据离开你的应用程序之前筛选掉它。

  1. 排除多个 HTTP 检测库提供的 URL 选项。

    以下示例演示如何排除使用 HTTP/HTTPS 检测库跟踪的某个 URL:

    import { useAzureMonitor, AzureMonitorOpenTelemetryOptions } from "@azure/monitor-opentelemetry";
    import { IncomingMessage } from "http";
    import { RequestOptions } from "https";
    import { HttpInstrumentationConfig } from "@opentelemetry/instrumentation-http";
    
    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。 使用添加自定义属性示例,但替换以下代码行:

    ...
    import { SpanKind, TraceFlags } from "@opentelemetry/api";
    import { ReadableSpan, SpanProcessor } from "@opentelemetry/sdk-trace-base";
    
    class SpanEnrichingProcessor implements SpanProcessor {
        ...
    
        onEnd(span: ReadableSpan) {
            if(span.kind == SpanKind.INTERNAL){
                span.spanContext().traceFlags = TraceFlags.NONE;
            }
        }
    }
    

自定义遥测

本部分介绍如何从应用程序收集自定义遥测数据。

添加自定义指标

你可能想要收集检测库收集的指标之外的指标。

OpenTelemetry API 提供六种指标“工具”来涵盖各种指标方案,在指标资源管理器中可视化指标时,需要选择正确的“聚合类型”。 使用 OpenTelemetry 指标 API 发送指标和使用检测库时,此要求是正确的。

下表显示了每个 OpenTelemetry Metric Instruments 的建议聚合类型]。

OpenTelemetry 检测 Azure Monitor 聚合类型
计数器 Sum
异步计数器 Sum
直方图 平均值、求和、计数(仅 Python 和 Node.js 的最大值、最小值)
异步仪表 平均值
UpDownCounter(仅 Python 和 Node.js) Sum
异步 UpDownCounter(仅 Python 和 Node.js) Sum

谨慎: 超出表中显示的聚合类型通常没有意义。

OpenTelemetry 规范介绍了这些检测,并提供了何时可以使用每种检测的示例。

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

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

let histogram = meter.createHistogram("histogram");
let counter = meter.createCounter("counter");
let gauge = meter.createObservableGauge("gauge");
gauge.addCallback((observableResult: ObservableResult) => {
    let 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" });

添加自定义异常

选择检测库会自动支持 Application Insights 的异常。 但是,你可能希望手动报告检测库报告之外的异常。 例如,代码捕获的异常通常 不会 报告,你可能希望报告这些异常,从而在相关体验(包括故障边栏选项卡和端到端事务视图)中引起注意。

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

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

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

故障排除

自我诊断

Azure Monitor OpenTelemetry 将 OpenTelemetry API 记录器用于内部日志。 若要启用它,请使用以下代码:

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

process.env.APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL = "VERBOSE";
process.env.APPLICATIONINSIGHTS_LOG_DESTINATION = "file";
process.env.APPLICATIONINSIGHTS_LOGDIR = "C:/applicationinsights/logs";

useAzureMonitor();

APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL环境 varialbe 可用于设置所需的日志级别,支持以下值:NONE、、WARNERRORINFODEBUGVERBOSEALL

可以使用环境变量将日志放入本地文件 APPLICATIONINSIGHTS_LOG_DESTINATION ,支持的值为 filefile+console,默认情况下将在 tmp 文件夹上生成名为 applicationinsights.log 的文件, /tmp 包括 *nix 和 USERDIR/AppData/Local/Temp Windows 的所有日志。 可以使用环境变量配置 APPLICATIONINSIGHTS_LOGDIR 日志目录。

示例

有关一些冠军方案的完整示例,请参阅 samples/ 文件夹。

关键概念

有关 OpenTelemetry 项目的详细信息,请查看 OpenTelemetry 规范

插件注册表

若要查看是否已为正在使用的库创建插件,请检查 OpenTelemetry 注册表

如果无法在注册表中使用库,请随时在 中 opentelemetry-js-contrib建议新的插件请求。

贡献

若要为此库做出贡献,请阅读贡献指南,详细了解如何生成和测试代码。

曝光数