作業の開始
パッケージをインストールする
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);
選択肢 | 説明 | 既定値 |
---|---|---|
azureMonitorExporterOptions |
Azure Monitor OpenTelemetry エクスポーターの構成。 詳細はこちら | |
samplingRatio |
サンプリング比率は [0,1] の範囲の値を取る必要があり、1 はすべてのデータがサンプリングされ、0 はすべてのトレース データがサンプリングされます。 | 1 |
instrumentationOptions |
インストルメンテーションライブラリの設定。 詳細はこちら |
|
browserSdkLoaderOptions |
Web Instrumentationsの設定を許可します。 |
|
resource |
Opentelemetry リソース。 詳細はこちら | |
enableLiveMetrics |
ライブメトリクスを有効/無効にします。 | true |
enableStandardMetrics |
標準メトリックを有効/無効にします。 | true |
logRecordProcessors |
グローバル ロガー プロバイダーに登録するログ レコード プロセッサの配列。 | |
spanProcessors |
グローバル トレーサー プロバイダーに登録するスパン プロセッサの配列。 | |
enableTraceBasedSamplingForLogs |
トレースに基づくログ・サンプリングを使用可能にします。 | false |
enablePerformanceCounters |
パフォーマンス カウンターを有効にします。 | true |
オプションは、パッケージのインストールフォルダのルートフォルダの下にある設定ファイルapplicationinsights.json
@azure/monitor-opentelemetry例:node_modules/@azure/monitor-opentelemetry
を使用して設定できます。 これらの構成値は、すべての AzureMonitorOpenTelemetryClient インスタンスに適用されます。
{
"samplingRatio": 0.8,
"enableStandardMetrics": true,
"enableLiveMetrics": true,
"instrumentationOptions":{
"azureSdk": {
"enabled": false
}
},
...
}
カスタム JSON ファイルは、 APPLICATIONINSIGHTS_CONFIGURATION_FILE
環境変数を使用して提供できます。
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 Browser SDK Loader を使用すると、次の条件に当てはまる場合に、ノード サーバーの応答に Web SDK を挿入できます。
- 応答に状態コード
200
が含まれている。 - 応答メソッドが
GET
である。 - サーバーの応答には、
Conent-Type
html ヘッダーがあります。 - Server resonse には 、タグと タグの両方が含まれています。
- 応答に現在およびバックアップの Web インストルメンテーション CDN エンドポイントが含まれていない。 (現在およびバックアップの Web インストルメンテーション CDN エンドポイントはここにあります)
ブラウザSDKローダーの使用方法の詳細については、 こちらをご覧ください。
クラウド ロール名とクラウド ロール インスタンスを設定する
クラウドロール名とクラウドロールインスタンスは、 OpenTelemetry リソース 属性を使用して設定できます。
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);
リソースの標準属性については、「 リソースのセマンティック規則」を参照してください。
テレメトリの変更
このセクションでは、テレメトリを変更する方法について説明します。
スパン属性を追加する
スパン属性を追加するには、次の 2 つの方法のいずれかを使用します。
- インストルメンテーション ライブラリで提供されるオプションを使用する。
- カスタム スパン プロセッサを追加する。
これらの属性には、テレメトリへのカスタム プロパティの追加が含まれる可能性があります。
先端: インストルメンテーションライブラリによって提供されるオプションを使用する利点は、利用可能な場合、コンテキスト全体が利用可能であることです。 その結果、ユーザーは、追加する属性を選択したり、フィルター処理したりできます。 たとえば、HttpClient インストルメンテーション ライブラリの enrich オプションを使用すると、ユーザーは httpRequestMessage 自体にアクセスできます。 そこからは何でも選択して、属性として保存できます。
トレースへのカスタムプロパティの追加
スパンに追加した属性は、カスタム プロパティとしてエクスポートされます。
カスタム プロセッサの使用:
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, 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 には、さまざまなメトリック シナリオをカバーする 6 つのメトリック "インストゥルメンテーション" が用意されており、メトリックス エクスプローラーでメトリックを視覚化するときには、正しい "集計タイプ" を選択する必要があります。 この要件は、OpenTelemetry Metric API を使用してメトリックを送信する場合と、インストルメンテーション ライブラリを使用する場合に当てはまります。
次の表は、各 OpenTelemetry Metric Instruments の推奨される集計タイプを示しています。
OpenTelemetry インストルメント | Azure Monitor の集計の種類 |
---|---|
カウンタ | 合計 |
非同期カウンター | 合計 |
ヒストグラム | 平均、合計、カウント (Python と Node.js のみの Max, Min ) |
非同期ゲージ | 平均 |
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 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フォルダに生成され、すべてのログ、*nixの /tmp
、Windowsの USERDIR/AppData/Local/Temp
が含まれます。 ログディレクトリは、 APPLICATIONINSIGHTS_LOGDIR
環境変数を使用して構成できます。
例示
いくつかのチャンピオン シナリオの完全なサンプルについては、 samples/
フォルダーを参照してください。
重要な概念
OpenTelemetry プロジェクトの詳細については、 OpenTelemetry の仕様を確認してください。
プラグインレジストリ
使用しているライブラリのプラグインがすでに作成されているかどうかを確認するには、 OpenTelemetry Registryを確認してください。
レジストリにライブラリが見つからない場合は、 opentelemetry-js-contrib
で新しいプラグインリクエストを自由に提案してください。
投稿
このライブラリに投稿する場合は、コードをビルドしてテストする方法の詳細については、投稿ガイド を参照してください。
Azure SDK for JavaScript