このガイドでは、 Azure Monitor Application Insights 内で OpenTelemetry (OTel) インストルメンテーションを統合およびカスタマイズする方法について説明します。
OpenTelemetry の概念の詳細については、OpenTelemetry の概要または OpenTelemetry に関する FAQ に関する記事を参照してください。
自動データ収集
ディストリビューションは、OpenTelemetry のインストルメンテーション ライブラリをバンドルすることでデータを自動的に収集します。
インストルメンテーション ライブラリを含む
要求数
依存関係
ログ
Azure Monitor に送信されるログの数を減らすか増やすには、適切なログ レベルを設定するか、フィルターを適用するようにログ記録を構成します。 たとえば、 Warning
ログと Error
ログのみを OpenTelemetry/Azure Monitor に送信するように選択できます。 OpenTelemetry では、ログ ルーティングやフィルター処理は制御されません。 ILogger
構成によってこれらの決定が行われます。 ILogger
の構成の詳細については、「ログ記録の構成」を参照してください。
ILogger
の詳細については、「C# および .NET でのログ記録」と「コード例」を参照してください。
Azure Monitor エクスポーターにはインストルメンテーション ライブラリは含まれていません。
次のコード サンプルを使用して 、Azure ソフトウェア開発キット (SDK) から依存関係を収集し、ソースを手動でサブスクライブできます。
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
// The following line subscribes to dependencies emitted from Azure SDKs
.AddSource("Azure.*")
.AddAzureMonitorTraceExporter()
.AddHttpClientInstrumentation(o => o.FilterHttpRequestMessage = (_) =>
{
// Azure SDKs create their own client span before calling the service using HttpClient
// In this case, we would see two spans corresponding to the same operation
// 1) created by Azure SDK 2) created by HttpClient
// To prevent this duplication we are filtering the span from HttpClient
// as span from Azure SDK contains all relevant information needed.
var parentActivity = Activity.Current?.Parent;
if (parentActivity != null && parentActivity.Source.Name.Equals("Azure.Core.Http"))
{
return false;
}
return true;
})
.Build();
Azure Monitor に送信されるログの数を減らすか増やすには、適切なログ レベルを設定するか、フィルターを適用するようにログ記録を構成します。 たとえば、 Warning
ログと Error
ログのみを OpenTelemetry/Azure Monitor に送信するように選択できます。 OpenTelemetry では、ログ ルーティングやフィルター処理は制御されません。 ILogger
構成によってこれらの決定が行われます。 ILogger
の構成の詳細については、「ログ記録の構成」を参照してください。
要求数
- Java Message Service (JMS) コンシューマー
- Kafka コンシューマー
- ネッティ
- 石英
- RabbitMQ(メッセージブローカーソフトウェア)
- サーブレット
- Spring スケジュール
注意
サーブレットとNettyの自動計装は、Java EE、Jakarta EE、Spring Boot、Quarkus、Micronaut
など、ほとんどのJava HTTPサービスを網羅しています。
依存関係 (とダウンストリームへの分散トレースの伝達)
- Apache HttpClient
- Apache HttpAsyncClient
- AsyncHttpClient
- Google HttpClient
- gRPC
- java.net.HttpURLConnection (JavaのHTTP接続クラス)
- Java 11 HttpClient
- JAX-RS クライアント
- Jetty HttpClient
- JMS (Javaメッセージサービス)
- カフカ
- Netty クライアント
- OkHttp
- RabbitMQ(メッセージブローカーソフトウェア)
依存関係 (ダウンストリームへの分散トレースの伝達なし)
- Cassandra をサポートしています
- Java Database Connectivity (JDBC) をサポートします
- MongoDB (非同期と同期) をサポートします
- Redis (レタスとジェダイ) をサポート
メトリック
- Micrometer メトリック (Spring Boot アクチュエータ メトリックを含む)
- Java Management Extensions (JMX) のメトリック
ログ
- Logback (MDC のプロパティを含む) ¹
- Log4j (MDC/スレッド コンテキスト プロパティを含む) ¹
- JBoss ログ (MDC のプロパティを含む) ¹
- java.util.logging ¹
Azure Monitor が収集するログの数を減らすか増やすには、まず、アプリケーションのログ 記録ライブラリで目的のログ レベル ( WARNING
や ERROR
など) を設定します。
既定の収集
次の Azure SDK によって出力されるテレメトリは、既定で自動収集されます。
[//]: # "Azure Cosmos DB 4.22.0+ due to https://github.com/Azure/azure-sdk-for-java/pull/25571"
[//]: # "the remaining above names and links scraped from https://azure.github.io/azure-sdk/releases/latest/java.html"
[//]: # "and version synched manually against the oldest version in maven central built on azure-core 1.14.0"
[//]: # ""
[//]: # "var table = document.querySelector('#tg-sb-content > div > table')"
[//]: # "var str = ''"
[//]: # "for (var i = 1, row; row = table.rows[i]; i++) {"
[//]: # " var name = row.cells[0].getElementsByTagName('div')[0].textContent.trim()"
[//]: # " var stableRow = row.cells[1]"
[//]: # " var versionBadge = stableRow.querySelector('.badge')"
[//]: # " if (!versionBadge) {"
[//]: # " continue"
[//]: # " }"
[//]: # " var version = versionBadge.textContent.trim()"
[//]: # " var link = stableRow.querySelectorAll('a')[2].href"
[//]: # " str += '* [' + name + '](' + link + ') ' + version + '\n'"
[//]: # "}"
[//]: # "console.log(str)"
Spring Boot ネイティブ アプリケーションの要求
- Spring Web
- Spring Web MVC (Model-View-Controller)
- Spring WebFlux
Spring Boot ネイティブ アプリケーションの依存関係
メトリック
Spring Boot ネイティブ アプリケーションのログ
Azure Monitor が収集するログの数を減らすか増やすには、まず、アプリケーションのログ 記録ライブラリで目的のログ レベル ( WARNING
や ERROR
など) を設定します。
Quartz ネイティブ アプリケーションについては、Quarkus のドキュメントを参照してください。
Azure Monitor Application Insights Distro の一部として、以下の OpenTelemetry Instrumentation ライブラリが含まれています。 詳細については、JavaScript 用 Azure SDK に関するページを参照してください。
要求数
依存関係
ログ
Azure Monitor が収集するログの数を減らすか増やすには、まず、アプリケーションのログ 記録ライブラリで目的のログ レベル ( WARNING
や ERROR
など) を設定します。
インストルメンテーションは、AzureMonitorOpenTelemetryOptions
を使用して構成できます。
// Import Azure Monitor OpenTelemetry
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Import OpenTelemetry HTTP Instrumentation to get config type
const { HttpInstrumentationConfig } = require("@azure/monitor-opentelemetry");
// Import HTTP to get type
const { IncomingMessage } = require("http");
// Specific Instrumentation configs could be added
const httpInstrumentationConfig: HttpInstrumentationConfig = {
ignoreIncomingRequestHook: (request: IncomingMessage) => {
return false; //Return true if you want to ignore a specific request
},
enabled: true
};
// Instrumentations configuration
const options: AzureMonitorOpenTelemetryOptions = {
instrumentationOptions: {
http: httpInstrumentationConfig,
azureSdk: { enabled: true },
mongoDb: { enabled: true },
mySql: { enabled: true },
postgreSql: { enabled: true },
redis: { enabled: true },
redis4: { enabled: true },
}
};
// Enable Azure Monitor integration
useAzureMonitor(options);
要求数
依存関係
ログ
Azure Monitor が収集するログの数を減らすか増やすには、まず、アプリケーションのログ 記録ライブラリで目的のログ レベル ( WARNING
や ERROR
など) を設定します。
Python ログ ライブラリの使用例は、 [GitHub] にあります。
Azure ソフトウェア開発キット (SDK) によって生成されたテレメトリは、既定で自動的に 収集されます 。
脚注
- ¹: "ハンドルされない/キャッチされない" 例外の自動レポートをサポートします
- ²: OpenTelemetry メトリックをサポートします
ヒント
インストルメンテーション ライブラリから自動的に収集されたか、またはカスタム コーディングから手動で収集されたかに関係なく、すべての OpenTelemetry メトリックは、現在、課金目的で Application Insights の "カスタム メトリック" と見なされます。 詳細情報。
OpenTelemetry コミュニティからインストルメンテーション ライブラリを含めると、より多くのデータを自動的に収集できます。
注意事項
コミュニティ インストルメンテーション ライブラリの品質は、サポートおよび保証していません。 ディストリビューションについてのご提案は、フィードバック コミュニティで投稿するか賛成に投票してください。 一部は実験的な OpenTelemetry 仕様に基づいており、今後、破壊的変更が生じる可能性があることにご注意ください。
コミュニティ ライブラリを追加するには、ライブラリの NuGet パッケージを追加した後、ConfigureOpenTelemetryMeterProvider
または ConfigureOpenTelemetryTracerProvider
メソッドを使用します。
次の例では、追加のメトリックを収集するためにランタイム インストルメンテーションを追加する方法を示します。
dotnet add package OpenTelemetry.Instrumentation.Runtime
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add runtime instrumentation.
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddRuntimeInstrumentation());
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
次の例では、追加のメトリックを収集するためにランタイム インストルメンテーションを追加する方法を示します。
// Create a new OpenTelemetry meter provider and add runtime instrumentation and the Azure Monitor metric exporter.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddRuntimeInstrumentation()
.AddAzureMonitorMetricExporter();
コミュニティ インストルメンテーション ライブラリを使用して Java Distro を拡張することはできません。 別のインストルメンテーション ライブラリを含めるように要求するには、GitHub ページで issue をオープンしてください。 GitHub ページへのリンクについては、[次の手順] を参照してください。
GraalVM Java ネイティブ アプリケーションでコミュニティ インストルメンテーション ライブラリを使用することはできません。
その他の OpenTelemetry インストルメンテーションについてはこちらから入手し、ApplicationInsightsClient の TraceHandler を使用して追加できます。
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics, trace, ProxyTracerProvider } = require("@opentelemetry/api");
// Import the OpenTelemetry instrumentation registration function and Express instrumentation
const { registerInstrumentations } = require( "@opentelemetry/instrumentation");
const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
// Get the OpenTelemetry tracer provider and meter provider
const tracerProvider = (trace.getTracerProvider() as ProxyTracerProvider).getDelegate();
const meterProvider = metrics.getMeterProvider();
// Enable Azure Monitor integration
useAzureMonitor();
// Register the Express instrumentation
registerInstrumentations({
// List of instrumentations to register
instrumentations: [
new ExpressInstrumentation(), // Express instrumentation
],
// OpenTelemetry tracer provider
tracerProvider: tracerProvider,
// OpenTelemetry meter provider
meterProvider: meterProvider
});
コミュニティ インストルメンテーション ライブラリ (正式にサポートされていない/Azure Monitor ディストリビューションに含まれていない) を追加するには、インストルメンテーションを直接使用してインストルメンテーションを実行できます。 コミュニティ インストルメンテーション ライブラリの一覧は、ここにあります。
注意
とディストリビューション instrument()
を使用してconfigure_azure_monitor()
を手動でインストルメント化することはお勧めしません。 これはサポートされているシナリオではなく、テレメトリに対して望ましくない動作が発生する可能性があります。
# Import the `configure_azure_monitor()`, `SQLAlchemyInstrumentor`, `create_engine`, and `text` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from sqlalchemy import create_engine, text
# Configure OpenTelemetry to use Azure Monitor.
configure_azure_monitor()
# Create a SQLAlchemy engine.
engine = create_engine("sqlite:///:memory:")
# SQLAlchemy instrumentation is not officially supported by this package, however, you can use the OpenTelemetry `instrument()` method manually in conjunction with `configure_azure_monitor()`.
SQLAlchemyInstrumentor().instrument(
engine=engine,
)
# Database calls using the SQLAlchemy library will be automatically captured.
with engine.connect() as conn:
result = conn.execute(text("select 'hello world'"))
print(result.all())
カスタム テレメトリを収集する
このセクションでは、アプリケーションからカスタム テレメトリを収集する方法について説明します。
言語とシグナルの種類によって、次のようにさまざまなカスタム テレメトリの収集方法があります。
- OpenTelemetry API(オープンテレメトリーAPI)
- 言語固有のログとメトリックのライブラリ
- Application Insights クラシック API
次の表は、現在サポートされているカスタム テレメトリの種類をまとめたものです。
言語 |
[カスタム イベント] |
カスタム メトリック |
依存関係 |
例外 |
ページ ビュー |
リクエスト |
トレース |
ASP.NET Core |
|
|
|
|
|
|
|
OpenTelemetry API(オープンテレメトリーAPI) |
|
はい |
はい |
はい |
|
はい |
|
ILogger API |
|
|
|
|
|
|
はい |
AI クラシック API |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ジャワ |
|
|
|
|
|
|
|
OpenTelemetry API(オープンテレメトリーAPI) |
|
はい |
はい |
はい |
|
はい |
|
Logback、Log4j 、JUL |
|
|
|
はい |
|
|
はい |
Micrometer メトリック |
|
はい |
|
|
|
|
|
AI クラシック API |
はい |
はい |
はい |
はい |
はい |
はい |
はい |
|
|
|
|
|
|
|
|
Node.js |
|
|
|
|
|
|
|
OpenTelemetry API(オープンテレメトリーAPI) |
|
はい |
はい |
はい |
|
はい |
|
|
|
|
|
|
|
|
|
パイソン |
|
|
|
|
|
|
|
OpenTelemetry API(オープンテレメトリーAPI) |
|
はい |
はい |
はい |
|
はい |
|
Python ログ モジュール |
|
|
|
|
|
|
はい |
イベント拡張機能 |
はい |
|
|
|
|
|
はい |
注意
Application Insights Java 3.x と Application Insights Node.js 3.x は、Application Insights クラシック API からテレメトリを収集します。 この動作により、OpenTelemetry API にすべてのカスタム テレメトリの種類が含まれるまで、アップグレードが簡略化され、カスタム テレメトリが一時的にサポートされます。
カスタム メトリックを追加する
このコンテキストでは、カスタム メトリック用語とは、OpenTelemetry インストルメンテーション ライブラリが自動的に収集するメトリック以外の追加のメトリックを収集するために、コードを手動でインストルメント化することを指します。
OpenTelemetry API には、さまざまなメトリック シナリオに対応する 6 つのメトリック "インストルメント" が用意されており、メトリックス エクスプローラーでメトリックを視覚化する場合は、適切な "集計の種類" を選択する必要があります。 この要件は、OpenTelemetry Metric API を使用してメトリックを送信する場合と、インストルメンテーション ライブラリを使用する場合に当てはまります。
次の表は、OpenTelemetry メトリック インストルメントごとに推奨される 集計の種類 を示しています。
OpenTelemetry インストルメント |
Azure Monitor の集計の種類 |
カウンタ |
SUM |
非同期カウンター |
SUM |
ヒストグラム |
Min、Max、Average、Sum、Count |
非同期ゲージ |
平均 |
アップダウンカウンター |
SUM |
非同期 UpDownCounter |
SUM |
注意事項
他の集計の種類は、ほとんどの場合意味がありません。
「OpenTelemetry の仕様」では、インストルメントについて説明し、それぞれを使用する場合の例を示します。
ヒント
ヒストグラムは最も汎用性が高く、Application Insights GetMetric Classic API と最も近いものです。 Azure Monitor では現在、ヒストグラム インストルメントがサポートされている 5 種類の集計にフラット化されており、パーセンタイルのサポートが進行中です。 汎用性は低くなりますが、他の OpenTelemetry 機器はアプリケーションのパフォーマンスに与える影響が小さくなります。
ヒストグラム例
アプリケーションのスタートアップでは、名前で Meter をサブスクライブする必要があります。
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter
は、同じ名前を使用して初期化する必要があります。
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new histogram metric named "FruitSalePrice".
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new Histogram metric named "FruitSalePrice".
// This metric will track the distribution of fruit sale prices.
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object. This object will be used to generate random sale prices.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
// Each record includes a timestamp, a value, and a set of attributes.
// The attributes can be used to filter and analyze the metric data.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
}
}
OpenTelemetry
を挿入します。
ヒストグラムを作成します。
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a histogram metric
let histogram = meter.createHistogram("histogram");
// Record values to the histogram metric with different tags
histogram.record(1, { "testKey": "testValue" });
histogram.record(30, { "testKey": "testValue2" });
histogram.record(100, { "testKey2": "testValue" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_histogram_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_histogram_demo")
# Record three values to the histogram.
histogram = meter.create_histogram("histogram")
histogram.record(1.0, {"test_key": "test_value"})
histogram.record(100.0, {"test_key2": "test_value"})
histogram.record(30.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
カウンターの例
アプリケーションのスタートアップでは、名前で Meter をサブスクライブする必要があります。
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter
は、同じ名前を使用して初期化する必要があります。
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new counter metric named "MyFruitCounter".
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new counter metric named "MyFruitCounter".
// This metric will track the number of fruits sold.
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
LongCounter myFruitCounter = meter
.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
}
}
OpenTelemetry
を挿入します。
カウンターを作成します。
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
LongCounter myFruitCounter = meter.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a counter metric
let counter = meter.createCounter("counter");
// Add values to the counter metric with different tags
counter.add(1, { "testKey": "testValue" });
counter.add(5, { "testKey2": "testValue" });
counter.add(3, { "testKey": "testValue2" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_counter_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_counter_demo")
# Create a counter metric with the name "counter".
counter = meter.create_counter("counter")
# Add three values to the counter.
# The first argument to the `add()` method is the value to add.
# The second argument is a dictionary of dimensions.
# Dimensions are used to group related metrics together.
counter.add(1.0, {"test_key": "test_value"})
counter.add(5.0, {"test_key2": "test_value"})
counter.add(3.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
ゲージの例
アプリケーションのスタートアップでは、名前で Meter をサブスクライブする必要があります。
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter
は、同じ名前を使用して初期化する必要があります。
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
}
}
OpenTelemetry
を挿入します。
ゲージを作成します。
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
// Import the useAzureMonitor function and the metrics module from the @azure/monitor-opentelemetry and @opentelemetry/api packages, respectively.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration.
useAzureMonitor();
// Get the meter for the "testMeter" meter name.
const meter = metrics.getMeter("testMeter");
// Create an observable gauge metric with the name "gauge".
let gauge = meter.createObservableGauge("gauge");
// Add a callback to the gauge metric. The callback will be invoked periodically to generate a new value for the gauge metric.
gauge.addCallback((observableResult: ObservableResult) => {
// Generate a random number between 0 and 99.
let randomNumber = Math.floor(Math.random() * 100);
// Set the value of the gauge metric to the random number.
observableResult.observe(randomNumber, {"testKey": "testValue"});
});
# Import the necessary packages.
from typing import Iterable
import os
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_gauge_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_gauge_demo")
# Define two observable gauge generators.
# The first generator yields a single observation with the value 9.
# The second generator yields a sequence of 10 observations with the value 9 and a different dimension value for each observation.
def observable_gauge_generator(options: CallbackOptions) -> Iterable[Observation]:
yield Observation(9, {"test_key": "test_value"})
def observable_gauge_sequence(options: CallbackOptions) -> Iterable[Observation]:
observations = []
for i in range(10):
observations.append(
Observation(9, {"test_key": i})
)
return observations
# Create two observable gauges using the defined generators.
gauge = meter.create_observable_gauge("gauge", [observable_gauge_generator])
gauge2 = meter.create_observable_gauge("gauge2", [observable_gauge_sequence])
# Wait for background execution.
input()
カスタム例外の追加
インストルメンテーション ライブラリを選ぶと、Application Insights の例外が自動的に報告されます。
ただし、インストルメンテーション ライブラリで報告される以外の例外を手動で報告することもできます。
たとえば、コードによってキャッチされた例外は、通常は報告されません。 エラー セクションやエンドツーエンドのトランザクション ビューなど、関連するエクスペリエンスで注目を集めるために、それらを報告することができます。
アクティビティを使用して例外をログに記録するには:
// Start a new activity named "ExceptionExample".
using (var activity = activitySource.StartActivity("ExceptionExample"))
{
// Try to execute some code.
try
{
throw new Exception("Test exception");
}
// If an exception is thrown, catch it and set the activity status to "Error".
catch (Exception ex)
{
activity?.SetStatus(ActivityStatusCode.Error);
activity?.RecordException(ex);
}
}
ILogger
を使用して例外をログに記録するには:
// Create a logger using the logger factory. The logger category name is used to filter and route log messages.
var logger = loggerFactory.CreateLogger(logCategoryName);
// Try to execute some code.
try
{
throw new Exception("Test Exception");
}
catch (Exception ex)
{
// Log an error message with the exception. The log level is set to "Error" and the event ID is set to 0.
// The log message includes a template and a parameter. The template will be replaced with the value of the parameter when the log message is written.
logger.Log(
logLevel: LogLevel.Error,
eventId: 0,
exception: ex,
message: "Hello {name}.",
args: new object[] { "World" });
}
アクティビティを使用して例外をログに記録するには:
// Start a new activity named "ExceptionExample".
using (var activity = activitySource.StartActivity("ExceptionExample"))
{
// Try to execute some code.
try
{
throw new Exception("Test exception");
}
// If an exception is thrown, catch it and set the activity status to "Error".
catch (Exception ex)
{
activity?.SetStatus(ActivityStatusCode.Error);
activity?.RecordException(ex);
}
}
ILogger
を使用して例外をログに記録するには:
// Create a logger using the logger factory. The logger category name is used to filter and route log messages.
var logger = loggerFactory.CreateLogger("ExceptionExample");
try
{
// Try to execute some code.
throw new Exception("Test Exception");
}
catch (Exception ex)
{
// Log an error message with the exception. The log level is set to "Error" and the event ID is set to 0.
// The log message includes a template and a parameter. The template will be replaced with the value of the parameter when the log message is written.
logger.Log(
logLevel: LogLevel.Error,
eventId: 0,
exception: ex,
message: "Hello {name}.",
args: new object[] { "World" });
}
opentelemetry-api
を使用して、スパンの状態を更新したり、例外を記録したりできます。
opentelemetry-api-1.0.0.jar
(以降) をアプリケーションに追加します。
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
状態を error
に設定し、コード内の例外を記録します。
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
状態を error
に設定し、コード内の例外を記録します。
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Node.js SDK は、最上位レベルのスパンまたはリモートまたは内部スパンの子に記録された場合にのみ、手動で記録されたスパンベースの例外を例外として Application Insights にエクスポートします。
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { trace } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the tracer for the "testTracer" namespace
const tracer = trace.getTracer("testTracer");
// Start a span with the name "hello"
let span = tracer.startSpan("hello");
// Try to throw an error
try {
throw new Error("Test Error");
}
// Catch the error and record it to the span
catch(error){
span.recordException(error);
}
OpenTelemetry Python SDK は、スローされた例外が自動的に取り込まれ、記録されるように実装されています。 この動作の例については、次のコード サンプルを参照してください。
# Import the necessary packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Get a tracer for the current module.
tracer = trace.get_tracer("otel_azure_monitor_exception_demo")
# Exception events
try:
# Start a new span with the name "hello".
with tracer.start_as_current_span("hello") as span:
# This exception will be automatically recorded
raise Exception("Custom exception message.")
except Exception:
print("Exception raised")
例外を手動で記録する場合は、コンテキスト マネージャー内でそのオプションを無効にし、次の例で示すように record_exception()
を直接使用できます。
...
# Start a new span with the name "hello" and disable exception recording.
with tracer.start_as_current_span("hello", record_exception=False) as span:
try:
# Raise an exception.
raise Exception("Custom exception message.")
except Exception as ex:
# Manually record exception
span.record_exception(ex)
...
カスタム スパンの追加
2 つのシナリオでカスタム スパンを追加することもできます。 最初に、インストルメンテーション ライブラリによってまだ収集されていない依存関係要求がある場合です。 2 つ目は、アプリケーション プロセスをエンドツーエンドのトランザクション ビューのスパンとしてモデル化する場合です。
注意
Activity
名前空間の ActivitySource
および System.Diagnostics
クラスは、それぞれ Span
と Tracer
の OpenTelemetry での概念を表しています。 ActivitySource
を使用する代わりに、コンストラクターを使用して TracerProvider
を直接作成します。 各 ActivitySource
クラスは、TracerProvider
を使用して AddSource()
に明示的に接続する必要があります。 これは、OpenTelemetry トレース API の一部が .NET ランタイムに直接組み込まれているためです。 詳細については、「Introduction to OpenTelemetry .NET Tracing API」 (OpenTelemetry .NET Tracing API の概要) を参照してください。
// Define an activity source named "ActivitySourceName". This activity source will be used to create activities for all requests to the application.
internal static readonly ActivitySource activitySource = new("ActivitySourceName");
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a source named "ActivitySourceName". This will ensure that all activities created by the activity source are traced.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Map a GET request to the root path ("/") to the specified action.
app.MapGet("/", () =>
{
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
// Return a response message.
return $"Hello World!";
});
// Start the ASP.NET Core application.
app.Run();
StartActivity
の既定値は ActivityKind.Internal
ですが、他の ActivityKind
を指定することもできます。
ActivityKind.Client
、ActivityKind.Producer
、ActivityKind.Internal
は、Application Insights の dependencies
にマップされます。
ActivityKind.Server
と ActivityKind.Consumer
は Application Insights の requests
にマップされます。
注意
Activity
名前空間の ActivitySource
および System.Diagnostics
クラスは、それぞれ Span
と Tracer
の OpenTelemetry での概念を表しています。 ActivitySource
を使用する代わりに、コンストラクターを使用して TracerProvider
を直接作成します。 各 ActivitySource
クラスは、TracerProvider
を使用して AddSource()
に明示的に接続する必要があります。 これは、OpenTelemetry トレース API の一部が .NET ランタイムに直接組み込まれているためです。 詳細については、「Introduction to OpenTelemetry .NET Tracing API」 (OpenTelemetry .NET Tracing API の概要) を参照してください。
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("ActivitySourceName")
.AddAzureMonitorTraceExporter()
.Build();
// Create an activity source named "ActivitySourceName".
var activitySource = new ActivitySource("ActivitySourceName");
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
StartActivity
の既定値は ActivityKind.Internal
ですが、他の ActivityKind
を指定することもできます。
ActivityKind.Client
、ActivityKind.Producer
、ActivityKind.Internal
は、Application Insights の dependencies
にマップされます。
ActivityKind.Server
と ActivityKind.Consumer
は Application Insights の requests
にマップされます。
OpenTelemetry の注釈を使用する
独自のスパンを追加する最も簡単な方法は、OpenTelemetry の @WithSpan
注釈を使用することです。
スパンによって、Application Insights の requests
と dependencies
テーブルが入力されます。
opentelemetry-instrumentation-annotations-1.32.0.jar
(以降) をアプリケーションに追加します。
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.32.0</version>
</dependency>
@WithSpan
注釈を使用して、メソッドが実行されるたびにスパンを出力します。
import io.opentelemetry.instrumentation.annotations.WithSpan;
@WithSpan(value = "your span name")
public void yourMethod() {
}
既定では、スパンは最終的に依存関係の種類 dependencies
で InProc
テーブルに入ります。
自動インスツルメンテーションによってキャプチャされないバックグラウンド ジョブを表すメソッドの場合は、属性 kind = SpanKind.SERVER
を @WithSpan
アノテーションに適用して、Application Insights の requests
テーブルに確実に表示されるようにすることをお勧めします。
OpenTelemetry API を使用する
前述の OpenTelemetry @WithSpan
注釈がニーズを満たさない場合は、OpenTelemetry API を使用してスパンを追加できます。
opentelemetry-api-1.0.0.jar
(以降) をアプリケーションに追加します。
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
GlobalOpenTelemetry
クラスを使用して Tracer
を作成します。
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = GlobalOpenTelemetry.getTracer("com.example");
スパンを作成し、最新の状態にしてから終了します。
Span span = tracer.spanBuilder("my first span").startSpan();
try (Scope ignored = span.makeCurrent()) {
// do stuff within the context of this
} catch (Throwable t) {
span.recordException(t);
} finally {
span.end();
}
OpenTelemetry
を挿入します。
Tracer
を作成します。
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = openTelemetry.getTracer("com.example");
スパンを作成し、最新の状態にしてから終了します。
Span span = tracer.spanBuilder("my first span").startSpan();
try (Scope ignored = span.makeCurrent()) {
// do stuff within the context of this
} catch (Throwable t) {
span.recordException(t);
} finally {
span.end();
}
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { trace } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the tracer for the "testTracer" namespace
const tracer = trace.getTracer("testTracer");
// Start a span with the name "hello"
let span = tracer.startSpan("hello");
// End the span
span.end();
OpenTelemetry API を使用して、Application Insights の requests
テーブルと dependencies
テーブルに表示される独自のスパンを追加できます。
このコード例では、tracer.start_as_current_span()
メソッドの使用を開始する方法、スパンを現在のスパンにする方法、およびそのコンテキスト内で終了する方法を示します。
...
# Import the necessary packages.
from opentelemetry import trace
# Get a tracer for the current module.
tracer = trace.get_tracer(__name__)
# Start a new span with the name "my first span" and make it the current span.
# The "with" context manager starts, makes the span current, and ends the span within it's context
with tracer.start_as_current_span("my first span") as span:
try:
# Do stuff within the context of this span.
# All telemetry generated within this scope will be attributed to this span.
except Exception as ex:
# Record the exception on the span.
span.record_exception(ex)
...
既定では、スパンは依存関係の種類 dependencies
で InProc
テーブルに入ります。
メソッドが自動インスツルメンテーションによってまだキャプチャされていないバックグラウンド ジョブを表す場合は、属性 kind = SpanKind.SERVER
を設定して、Application Insights の requests
テーブルに確実に表示されるようにすることをお勧めします。
...
# Import the necessary packages.
from opentelemetry import trace
from opentelemetry.trace import SpanKind
# Get a tracer for the current module.
tracer = trace.get_tracer(__name__)
# Start a new span with the name "my request span" and the kind set to SpanKind.SERVER.
with tracer.start_as_current_span("my request span", kind=SpanKind.SERVER) as span:
# Do stuff within the context of this span.
...
カスタム イベントを送信する
Application Insights では、customEvents
テーブルにカスタム イベントが格納されます。 それらを 分析、フィルター処理、視覚化 する 1 つの方法は、 Application Insights の使用エクスペリエンスを使用することです。
クライアント側の相互作用イベントの収集を自動化する場合は、 JavaScript SDK でプラグインを使用できます。
カスタム イベントはパブリック プレビュー段階であり、 Azure.Monitor.OpenTelemetry.AspNetCore
1.3.0-beta.3 を使用します。
CustomEvent
を使用してILogger
を送信するには、メッセージ テンプレートで"microsoft.custom_event.name"
属性を設定します。
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
カスタム イベントはパブリック プレビュー段階にあり、 Azure.Monitor.OpenTelemetry.Exporter
1.4.0-beta.3 を使用します。
CustomEvent
を使用してILogger
を送信するには、メッセージ テンプレートで"microsoft.custom_event.name"
属性を設定します。
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
Java エージェントで customEvent
を送信するには、OpenTelemetry ログ レコードに "microsoft.custom_event.name"
属性を設定します。
Application Insights Java エージェントが使用されているか、自動構成 SDK であるかによって、OpenTelemetry ロガーをフェッチする方法が若干異なります。 この詳細については、次の例で詳しく説明します。
Application Insights Java エージェントの場合:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Severity;
Logger logger = GlobalOpenTelemetry.get().getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),"test-event-name")
.setSeverity(Severity.INFO)
.emit();
自動構成 SDK の場合:
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure;
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigureOptions;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder;
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorAutoConfigureOptions options = new AzureMonitorAutoConfigureOptions();
options.connectionString("<your connection string>");
AzureMonitorAutoConfigure.customize(sdkBuilder, options);
OpenTelemetry openTelemetry = sdkBuilder.build().getOpenTelemetrySdk();
Logger logger = openTelemetry.getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),"test-event-name")
.setSeverity(Severity.INFO)
.emit();
カスタム イベントを確実に出力するには、OpenTelemetry API を直接使用します。 一部のログ 記録フレームワークでは、カスタム イベント属性の追加または解析がサポートされていません。
Java ネイティブで customEvent
属性を使用して"microsoft.custom_event.name"
を送信することはできません。
customEvent
を使用してlogger.emit
を送信するには、ログの"microsoft.custom_event.name"
オブジェクトにattributes
属性を設定します。 その他の属性は、必要に応じて含めることもできます。
// Send a customEvent by including the microsoft attribute key in the log.
// The customEvent name uses the value of that attribute.
logger.emit({
body: 'Hello World!',
attributes: {
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1"
},
});
// You can also populate fields like client_IP with attribute `client.address`
logger.emit({
body: 'This entry will have a custom client_IP',
attributes: {
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1"
},
});
Python でcustomEvent
を送信するには、"microsoft.custom_event.name"
パラメーターで extra
属性を持つログ ライブラリを使用します。
import logging
from azure.monitor.opentelemetry import configure_azure_monitor
# Set up your application logger
logger = logging.getLogger("my-app-logger")
# Configure Azure Monitor to collect logs from the specified logger name
configure_azure_monitor(
logger_name="my-app-logger", # Collect logs from your namespaced logger
)
# Log a custom event with a custom name and additional attribute
# The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.warning(
"Hello World!",
extra={
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1"
}
)
# You can also populate fields like client_IP with attribute `client.address`
logger.info(
"This entry will have a custom client_IP",
extra={
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1"
}
)
テレメトリの変更
このセクションでは、テレメトリを変更する方法について説明します。
スパン属性を追加する
これらの属性には、テレメトリへのカスタム プロパティの追加が含まれる可能性があります。 また、属性を使用して、Application Insights スキーマに [クライアント IP] などのオプション フィールドを設定することもできます。
スパンにカスタム プロパティを追加する
スパンに追加した属性は、カスタム プロパティとしてエクスポートされます。 これらは、要求、依存関係、トレース、または例外テーブルの customDimensions フィールドに設定されます。
スパン属性を追加するには、次の 2 つの方法のいずれかを使用します。
ヒント
インストルメンテーション ライブラリで提供されるオプションを使用できる利点は、コンテキスト全体を使用できることです。 その結果、ユーザーは、追加する属性を選択したり、フィルター処理したりできます。 たとえば、HttpClient インストルメンテーション ライブラリの enrich オプションを使用すると、ユーザーは HttpRequestMessage や HttpResponseMessage 自体にアクセスできます。 そこからは何でも選択して、属性として保存できます。
多くのインストルメンテーション ライブラリには、強化オプションが用意されています。 ガイダンスについては、個々のインストルメンテーション ライブラリの Readme ファイルを参照してください。
カスタム プロセッサの使用:
ヒント
ここに示すプロセッサを、Azure Monitor を追加する前に追加します。
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a new processor named ActivityEnrichingProcessor.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityEnrichingProcessor()));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Start the ASP.NET Core application.
app.Run();
次のコードを使用して、プロジェクトに ActivityEnrichingProcessor.cs
を追加します。
public class ActivityEnrichingProcessor : BaseProcessor<Activity>
{
public override void OnEnd(Activity activity)
{
// The updated activity will be available to all processors which are called after this processor.
activity.DisplayName = "Updated-" + activity.DisplayName;
activity.SetTag("CustomDimension1", "Value1");
activity.SetTag("CustomDimension2", "Value2");
}
}
スパン属性を追加するには、次の 2 つの方法のいずれかを使用します。
- インストルメンテーション ライブラリで提供されるオプションを使用する。
- カスタム スパン プロセッサを追加する。
ヒント
インストルメンテーション ライブラリで提供されるオプションを使用できる利点は、コンテキスト全体を使用できることです。 その結果、ユーザーは、追加する属性を選択したり、フィルター処理したりできます。 たとえば、HttpClient インストルメンテーション ライブラリの enrich オプションを使用すると、ユーザーは httpRequestMessage 自体にアクセスできます。 そこからは何でも選択して、属性として保存できます。
多くのインストルメンテーション ライブラリには、強化オプションが用意されています。 ガイダンスについては、個々のインストルメンテーション ライブラリの Readme ファイルを参照してください。
カスタム プロセッサの使用:
ヒント
ここに示すプロセッサを、Azure Monitor エクスポーターの前に追加します。
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
// Add a source named "OTel.AzureMonitor.Demo".
.AddSource("OTel.AzureMonitor.Demo") // Add a new processor named ActivityEnrichingProcessor.
.AddProcessor(new ActivityEnrichingProcessor()) // Add the Azure Monitor trace exporter.
.AddAzureMonitorTraceExporter() // Add the Azure Monitor trace exporter.
.Build();
次のコードを使用して、プロジェクトに ActivityEnrichingProcessor.cs
を追加します。
public class ActivityEnrichingProcessor : BaseProcessor<Activity>
{
// The OnEnd method is called when an activity is finished. This is the ideal place to enrich the activity with additional data.
public override void OnEnd(Activity activity)
{
// Update the activity's display name.
// The updated activity will be available to all processors which are called after this processor.
activity.DisplayName = "Updated-" + activity.DisplayName;
// Set custom tags on the activity.
activity.SetTag("CustomDimension1", "Value1");
activity.SetTag("CustomDimension2", "Value2");
}
}
opentelemetry-api
を使用して、スパンに属性を追加することができます。
1 つ以上のスパン属性を追加すると、customDimensions
、requests
、dependencies
、または traces
テーブル内の exceptions
フィールドにデータが入力されます。
opentelemetry-api-1.0.0.jar
(以降) をアプリケーションに追加します。
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
コードにカスタム ディメンションを追加します:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
コードにカスタム ディメンションを追加します:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
// Import the necessary packages.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { ReadableSpan, Span, SpanProcessor } = require("@opentelemetry/sdk-trace-base");
const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
forceFlush(): Promise<void> {
return Promise.resolve();
}
shutdown(): Promise<void> {
return Promise.resolve();
}
onStart(_span: Span): void {}
onEnd(span: ReadableSpan) {
// Add custom dimensions to the span.
span.attributes["CustomDimension1"] = "value1";
span.attributes["CustomDimension2"] = "value2";
}
}
// Enable Azure Monitor integration.
const options: AzureMonitorOpenTelemetryOptions = {
// Add the SpanEnrichingProcessor
spanProcessors: [new SpanEnrichingProcessor()]
}
useAzureMonitor(options);
カスタム プロセッサの使用:
...
# Import the necessary packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Create a SpanEnrichingProcessor instance.
span_enrich_processor = SpanEnrichingProcessor()
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
# Configure the custom span processors to include span enrich processor.
span_processors=[span_enrich_processor],
)
...
次のコードを使用して、プロジェクトに SpanEnrichingProcessor
を追加します。
# Import the SpanProcessor class from the opentelemetry.sdk.trace module.
from opentelemetry.sdk.trace import SpanProcessor
class SpanEnrichingProcessor(SpanProcessor):
def on_end(self, span):
# Prefix the span name with the string "Updated-".
span._name = "Updated-" + span.name
# Add the custom dimension "CustomDimension1" with the value "Value1".
span._attributes["CustomDimension1"] = "Value1"
# Add the custom dimension "CustomDimension2" with the value "Value2".
span._attributes["CustomDimension2"] = "Value2"
ユーザー IP を設定する
スパンに属性を設定することで、要求の client_IP フィールドにデータを入力できます。 Application Insights では、この IP アドレスを使用してユーザーの位置属性を生成した後、既定でそれを破棄します。
カスタム プロパティの例を使用しますが、次の ActivityEnrichingProcessor.cs
のコード行を置き換えます。
// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("client.address", "<IP Address>");
カスタム プロパティの例を使用しますが、次の ActivityEnrichingProcessor.cs
のコード行を置き換えます。
// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("client.address", "<IP Address>");
このフィールドは Java によって自動的に設定されます。
カスタム プロパティの追加の例を使用しますが、次のコード行を置き換えます。
...
// Import the SemanticAttributes class from the @opentelemetry/semantic-conventions package.
const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
onEnd(span) {
// Set the HTTP_CLIENT_IP attribute on the span to the IP address of the client.
span.attributes[SemanticAttributes.HTTP_CLIENT_IP] = "<IP Address>";
}
}
カスタム プロパティの例を使用しますが、次の SpanEnrichingProcessor.py
のコード行を置き換えます。
# Set the `http.client_ip` attribute of the span to the specified IP address.
span._attributes["http.client_ip"] = "<IP Address>"
ユーザー ID または認証されたユーザー ID を設定する
次のガイダンスを参考にして、要求の user_Id または user_AuthenticatedId フィールドを設定できます。 ユーザー ID は匿名のユーザー識別子です。 認証されたユーザー ID は既知のユーザー識別子です。
重要
認証されたユーザー ID を設定する前に、該当するプライバシーに関する法律を調べてください。
カスタム プロパティの例を使用します。
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<User Id>");
カスタム プロパティの例を使用します。
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<User Id>");
user ID
、requests
、または dependencies
テーブルの exceptions
フィールドに入力します。
opentelemetry-api-1.0.0.jar
(以降) をアプリケーションに追加します。
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
コードに user_Id
を設定します。
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser");
user ID
、requests
、または dependencies
テーブルの exceptions
フィールドに入力します。
コードに user_Id
を設定します。
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser");
カスタム プロパティの追加の例を使用しますが、次のコード行を置き換えます。
...
// Import the SemanticAttributes class from the @opentelemetry/semantic-conventions package.
import { SemanticAttributes } from "@opentelemetry/semantic-conventions";
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
onEnd(span: ReadableSpan) {
// Set the ENDUSER_ID attribute on the span to the ID of the user.
span.attributes[SemanticAttributes.ENDUSER_ID] = "<User ID>";
}
}
カスタム プロパティの追加の例を使用しますが、次のコード行を置き換えます。
# Set the `enduser.id` attribute of the span to the specified user ID.
span._attributes["enduser.id"] = "<User ID>"
ログ属性の追加
OpenTelemetry は .NET の ILogger
を使用します。
カスタム ディメンションをログに添付するには、 [メッセージ テンプレート] を使用します。
OpenTelemetry は .NET の ILogger
を使用します。
カスタム ディメンションをログに添付するには、 [メッセージ テンプレート] を使用します。
Logback、Log4j、java.util.logging は自動的にインストルメント化されます。 カスタム ディメンションのログへのアタッチは、次の方法で実行できます。
Spring Boot ネイティブ アプリケーションの場合、Logback はすぐにインストルメント化されます。
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const bunyan = require('bunyan');
// Instrumentations configuration
const options: AzureMonitorOpenTelemetryOptions = {
instrumentationOptions: {
// Instrumentations generating logs
bunyan: { enabled: true },
}
};
// Enable Azure Monitor integration
useAzureMonitor(options);
var log = bunyan.createLogger({ name: 'testApp' });
log.info({
"testAttribute1": "testValue1",
"testAttribute2": "testValue2",
"testAttribute3": "testValue3"
}, 'testEvent');
Python ログ ライブラリは、自動インストルメント化されます。 ログの extra
引数にディクショナリを渡すことで、ログにカスタム ディメンションをアタッチできます。
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
トレース ID またはスパン ID を取得する
次の手順を使って、現在アクティブなスパンの Trace ID
と Span ID
を取得できます。
注意
Activity
名前空間の ActivitySource
および System.Diagnostics
クラスは、それぞれ Span
と Tracer
の OpenTelemetry での概念を表しています。 これは、OpenTelemetry トレース API の一部が .NET ランタイムに直接組み込まれているためです。 詳細については、「Introduction to OpenTelemetry .NET Tracing API」 (OpenTelemetry .NET Tracing API の概要) を参照してください。
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
注意
Activity
名前空間の ActivitySource
および System.Diagnostics
クラスは、それぞれ Span
と Tracer
の OpenTelemetry での概念を表しています。 これは、OpenTelemetry トレース API の一部が .NET ランタイムに直接組み込まれているためです。 詳細については、「Introduction to OpenTelemetry .NET Tracing API」 (OpenTelemetry .NET Tracing API の概要) を参照してください。
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
opentelemetry-api
を使用して、トレース ID またはスパン ID を取得することができます。
opentelemetry-api-1.0.0.jar
(以降) をアプリケーションに追加します。
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
コードで要求のトレース ID とスパン ID を取得します。
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
コードで要求のトレース ID とスパン ID を取得します。
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
コードで要求のトレース ID とスパン ID を取得します。
// Import the trace module from the OpenTelemetry API.
const { trace } = require("@opentelemetry/api");
// Get the span ID and trace ID of the active span.
let spanId = trace.getActiveSpan().spanContext().spanId;
let traceId = trace.getActiveSpan().spanContext().traceId;
コードで要求のトレース ID とスパン ID を取得します。
# Import the necessary libraries.
from opentelemetry import trace
# Get the trace ID and span ID of the current span.
trace_id = trace.get_current_span().get_span_context().trace_id
span_id = trace.get_current_span().get_span_context().span_id
次のステップ