你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
入门指南
安装软件包
npm install @azure/monitor-opentelemetry
当前支持的环境
警告: 此 SDK 仅适用于 Node.js 环境。 将 Application Insights JavaScript SDK 用于 Web 和浏览器方案。
有关详细信息,请参阅我们的 支持策略。
先决条件
启用 Azure Monitor OpenTelemetry 客户端
重要:
useAzureMonitor
必须在导入任何其他内容 之前 调用。 如果先导入其他库,则可能会导致遥测丢失。
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
.
配置
import { resourceFromAttributes } from "@opentelemetry/resources";
import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";
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 },
},
enableLiveMetrics: true,
enableStandardMetrics: true,
browserSdkLoaderOptions: {
enabled: false,
connectionString: "",
},
resource: resource,
logRecordProcessors: [],
spanProcessors: [],
};
useAzureMonitor(options);
选项 | DESCRIPTION | 违约 |
---|---|---|
azureMonitorExporterOptions |
Azure Monitor OpenTelemetry 导出器配置。 更多信息请点击这里 | |
samplingRatio |
采样率必须取 [0,1] 范围内的值,1 表示将对所有数据进行采样,0 表示将采样所有 Tracing 数据。 | 1 |
instrumentationOptions |
检测库配置。 更多信息请点击这里 |
|
browserSdkLoaderOptions |
允许配置 Web Instrumentations。 |
|
resource |
Opentelemetry 资源。 更多信息请点击这里 | |
enableLiveMetrics |
启用/禁用实时指标。 | true |
enableStandardMetrics |
启用/禁用标准指标。 | true |
logRecordProcessors |
要注册到全局记录器提供程序的日志记录处理器数组。 | |
spanProcessors |
要注册到全局跟踪器提供程序的 span 处理器数组。 | |
enableTraceBasedSamplingForLogs |
启用基于跟踪的日志采样。 | false |
enablePerformanceCounters |
启用性能计数器。 | true |
可以使用位于包安装文件夹根@azure/monitor-opentelemetry文件夹下的配置文件applicationinsights.json
设置选项,例如:node_modules/@azure/monitor-opentelemetry
。 这些配置值将应用于所有 AzureMonitorOpenTelemetryClient 实例。
{
"samplingRatio": 0.8,
"enableStandardMetrics": true,
"enableLiveMetrics": true,
"instrumentationOptions":{
"azureSdk": {
"enabled": false
}
},
...
}
可以使用 APPLICATIONINSIGHTS_CONFIGURATION_FILE
environment variable 提供自定义 JSON 文件。
process.env["APPLICATIONINSIGHTS_CONFIGURATION_FILE"] = "path/to/customConfig.json";
仪表库
以下 OpenTelemetry 检测库包含在 Azure Monitor OpenTelemetry 中。
警告: 插桩库基于实验性 OpenTelemetry 规范。 Microsoft 的预览版 支持承诺是确保以下库向 Azure Monitor Application Insights 发出数据,但中断性变更或实验性映射可能会阻止某些数据元素。
分布式跟踪
指标
日志
此处提供了其他 OpenTelemetry 检测,可以使用 AzureMonitorOpenTelemetryClient 中的 TracerProvider 添加这些检测。
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 浏览器 SDK 加载程序
当满足以下条件时,Application Insights 浏览器 SDK 加载程序允许将 Web SDK 注入节点服务器响应:
- 响应的状态代码为
200
。 - 响应方法为
GET
。 - 服务器响应具有
Conent-Type
html 标头。 - Server resonse 同时包含 and 标签。
- 响应不包含当前的 /backup Web Instrumentation CDN 终结点。 (此处为当前和备份 Web 仪表 CDN 端点)
有关浏览器 SDK 加载程序使用的更多信息, 请参阅此处。
设置云角色名称和云角色实例
您可以通过 OpenTelemetry Resource 属性设置 Cloud Role Name 和 Cloud Role Instance。
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 = Resource.EMPTY;
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);
有关资源的标准属性的信息,请参阅 资源语义约定。
修改遥测
本部分介绍如何修改遥测。
添加范围属性
若要添加范围属性,请使用以下两种方法之一:
- 使用检测库提供的选项。
- 添加自定义范围处理器。
这些属性可能包括向遥测添加自定义属性。
提示: 使用插桩库提供的选项(如果可用)的优点是整个上下文都可用。 因此,用户可以选择添加或筛选更多属性。 例如,HttpClient 检测库中的扩充选项允许用户访问 httpRequestMessage 本身。 他们可以从中选择任何内容并将其存储为属性。
向 Trace 添加自定义属性
你添加到范围的任何属性都将导出为自定义属性。
使用自定义处理器:
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);
将作名称添加到跟踪和日志
使用自定义 span 处理器和日志记录处理器,以便将请求中的作名称附加到依赖项和日志并与之关联。
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, LogRecord } 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: LogRecord, _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);
筛选遥测数据
您可以使用以下方法在遥测数据离开应用程序之前筛选掉它。
排除许多 HTTP 检测库提供的 URL 选项。
以下示例演示如何使用 HTTP/HTTPS 监控库排除被跟踪的某个 URL:
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);
使用自定义处理器。 你可以使用自定义范围处理器来排除导出某些范围。 若要将范围标记为不导出,请将
TraceFlag
设置为DEFAULT
。 使用添加 自定义属性示例,但替换以下代码行: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; } } }
自定义遥测
本部分介绍如何从应用程序收集自定义遥测数据。
添加自定义指标
您可能希望收集的指标超出 检测库收集的指标。
OpenTelemetry API 提供了六个指标“工具”来涵盖各种指标场景,在 Metrics Explorer 中可视化指标时,您需要选择正确的“聚合类型”。 使用 OpenTelemetry 指标 API 发送指标和使用检测库时,此要求是正确的。
下表显示了每个 OpenTelemetry Metric Instruments 的建议聚合类型]。
OpenTelemetry 工具 | Azure Monitor 聚合类型 |
---|---|
计数器 | 总和 |
异步计数器 | 总和 |
直方图 | 平均值、总和、计数(最大值、最小值仅适用于 Python 和 Node.js) |
异步仪表 | 平均值 |
UpDownCounter(仅限 Python 和 Node.js) | 总和 |
异步 UpDownCounter(仅限 Python 和 Node.js) | 总和 |
谨慎: 超出表中所示值的聚合类型通常没有意义。
OpenTelemetry 规范详细描述了这些工具,并提供了何时使用每种工具的示例。
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" });
添加自定义例外
选择检测库会自动支持 Application Insights 的异常。 但是,您可能希望手动报告超出插桩库报告的异常。 例如,您的代码捕获的异常通常 不会 报告,您可能希望报告它们,从而在相关体验(包括故障边栏选项卡和端到端事务视图)中引起对它们的注意。
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 OpenTelemetry 将 OpenTelemetry API 记录器用于内部日志。 要启用它,请使用以下代码:
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
、 ALL
WARN
INFO
DEBUG
VERBOSE
和 .
可以使用APPLICATIONINSIGHTS_LOG_DESTINATION
环境变量将日志放入本地文件,支持的值为 file
和 file+console
,默认情况下会在 tmp 文件夹中生成一个名为 applicationinsights.log
的文件,包括 *nix 和 USERDIR/AppData/Local/Temp
Windows 的所有日志/tmp
。 日志目录可以使用 APPLICATIONINSIGHTS_LOGDIR
环境变量进行配置。
例子
有关一些冠军场景的完整示例,请参阅文件夹 samples/
。
关键概念
有关 OpenTelemetry 项目的更多信息,请查看 OpenTelemetry 规范。
插件注册表
要查看是否已为您正在使用的库制作插件,请查看 OpenTelemetry 注册表。
如果您在注册表中找不到您的库,请随时在 上 opentelemetry-js-contrib
建议新的插件请求。
贡献
若要参与此库,请阅读 贡献指南 了解有关如何生成和测试代码的详细信息。