JavaScript 的 Azure 监视器打开遥测
开始
安装软件包
npm install @azure/monitor-opentelemetry
目前得到支持的环境
警告: 这个SDK只适用于Node.js环境. 使用 应用程序透视 JavaScript SDK 用于网页和浏览器设置.
看我们的 支助政策 更多细节.
先决条件
- 一个 Azure 订阅
- 一个 应用程序 Insights 工作空间
启用 Azure 监视器打开遥测客户端
重要内容:
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。 。 。 . - 批次跨度处理可以配置标准 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-环境-可变性/。 。 。 . - 用来使用 固定百分比采样器 (而不是默认的有限采样器),也可以:
- 设置环境变量
OTEL_TRACES_SAMPLER=microsoft.fixed_percentage带有可选OTEL_TRACES_SAMPLER_ARG关于取样概率(例如,0.550%). - 设定
tracesPerSecond: 0在 distro 选项中,该选项将禁用速率限制并返回使用samplingRatio固定百分比抽样.
- 设置环境变量
无害环境管理支助
说明: 无害环境管理支持需要18.19.0节点或以后。 关于在OpenTeleometry中支持无害环境管理的更详细情况,参见: 开放远程计量无害环境管理 辅助文件。 。 。 .
对于ECMAScript模块(ESM)应用,OpenTelemetry仪器化需要加载器钩被注册 在此之前 任何有仪器的模块( 如 http已装入。 这是无害环境管理的一项基本要求 -- -- 模块装入后无法装入仪器.
使用 --import 确保加载器在节点.js进程一开始就注册的旗帜。 替换 <your-app-entry-point> 与您应用程序主文件的路径( 例如 ), ./dist/index.js, (中文(简体) ), ./src/index.mjs, (中文(简体) ), ./server.js等 :
node --import @azure/monitor-opentelemetry/loader <your-app-entry-point>
比如说,你 package.json数字 :
{
"scripts": {
"start": "node --import @azure/monitor-opentelemetry/loader ./dist/index.js"
}
}
然后在您的申请条目文件中,拨打 useAzureMonitor() 来配置 SDK :
import { useAzureMonitor } from "@azure/monitor-opentelemetry";
useAzureMonitor({
azureMonitorExporterOptions: {
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,
},
});
对于CommonJS应用程序,不需要额外的旗帜- 包被导入时加载器会自动注册.
配置
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 导出器配置 . 这里有更多信息 | |
samplingRatio |
采样比必须在范围 [0,1] 取出一个值, 1 表示所有数据都会被采样,0 所有追踪数据都将被取出. 仅在 tracesPerSecond 设置为 0. |
1 |
tracesPerSecond |
使用有速率限制的采样器进行每秒采样的最大痕迹数. 设定为 0 以禁用速率限制并使用固定百分比抽样 samplingRatio 换句话说. |
5 |
instrumentationOptions |
仪器库配置. 这里有更多信息 |
|
browserSdkLoaderOptions |
允许配置 Web 仪器 . |
|
resource |
开口遥测资源. 这里有更多信息 | |
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,
无论远程设置如何。 缺少或无效的远程设置
状态;在第一个有效设置之前,应用本地配置.
{
"samplingRatio": 0.8,
"enableStandardMetrics": true,
"enableLiveMetrics": true,
"instrumentationOptions":{
"azureSdk": {
"enabled": false
}
},
...
}
自定义 JSON 文件可用 APPLICATIONINSIGHTS_CONFIGURATION_FILE 环境变量.
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发送数据,但突破变化或实验映射有可能会屏蔽一些数据元素.
分布式追踪
计量
日志
-
控制台 (默认损坏;启用方式
instrumentationOptions: { console: { enabled: true } }(中文(简体) )一旦启用, 一组
console收集的方法由logSeverity数值console返回到APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL环境变量( e)NONE, (中文(简体) ),ERROR, (中文(简体) ),WARN, (中文(简体) ),INFO, (中文(简体) ),DEBUG, (中文(简体) ),VERBOSE, (中文(简体) ),ALL; 见 自诊断当logSeverity未设置。 譬如说,WARN仅收集console.warn财务报告和审定财务报表console.error时NONE禁用收藏console(和所有其他) 完全的日志.
其他开放的遥测仪器 这里 并可以使用 AzureMonitor OpenTelemetricClient 中的 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()],
});
应用程序 Insights 浏览器 SDK 加载器
应用程序 Insights 浏览器 SDK 加载器允许您在以下条件属实时将web SDK注入节点服务器响应:
- 反应有状态代码
200。 。 。 . - 反应方法是
GET。 。 。 . - 服务器响应有:
Conent-Typehtml 标题. - 服务器共振包含两个和标签.
- 响应中不包含当前/备份的网络仪器CDN端点. (当前和备份的网络仪器 CDN 端点) 这里(中文(简体) )
关于浏览器SDK加载器使用情况的进一步信息可找到 这里。 。 。 .
设置云角色名和云角色实例
您可以通过 : 打开远程资源 属性.
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);
资源标准属性信息参见: 资源语义公约。 。 。 .
修改遥测
本节解释如何修改遥测.
添加跨度属性
要添加跨度属性,请使用以下两种方法:
- 使用由 仪器库。 。 。 .
- 添加自定义跨度处理器 .
这些属性可能包括在您的遥测中添加自定义属性 .
提示 : 使用仪器库提供的选项的优点是,在可用时,整个上下文都是可用的. 因此,用户可以选择添加或过滤更多属性. 例如,HttpClient 仪器库中的丰富选项让用户可以访问 httpRequestMessage 本身. 他们可以从中选择任何内容,并将其作为属性来存储.
添加自定义属性到 Track
任意 属性 以自定义属性导出.
使用自定义处理器 :
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);
将操作名称添加到跟踪和日志
使用自定义的跨度处理器和日志记录处理器,以便从请求中附加和关联操作名称到依赖和日志.
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);
过滤遥测
您可以使用下列方法过滤出遥测器 以免它离开您的应用程序 .
-
排除许多 HTTP 仪器库提供的 URL 选项 .
以下例子说明如何通过使用 HTTP/HTTPS 仪器库数字 :
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; } } }
自定义遥测
本节解释如何从您的应用程序中收集自定义遥测 .
添加自定义度量衡
您可能想要收集超过所收集的参数 仪器库。 。 。 .
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 规格 描述仪器,并举例说明您何时可以使用每个仪器.
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 的例外. 然而,您可能想要手动报告非仪器库报告的例外. 举例来说,你的代码所发现的例外 没有 通常不报告,你不妨报告 ,从而在相关经验中提请注意它们,包括故障刃和端到端的交易视图.
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进行内部日志. 要启用,请使用以下代码:
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/ 文件夹.
关键概念
关于OpenTeleometry项目的更多信息,请审查 OpenTeleometry 规格。 。 。 .
插件登记
要了解您是否已经为正在使用的库设置了插件, 请检查 OpenTeleometry 注册。 。 。 .
如果您无法在注册库中创建您的库, 请随意建议一个新的插件请求 opentelemetry-js-contrib。 。 。 .
捐款
如果您想为图书馆捐钱 请读一下 贡献指南 学习如何构建和测试密码.