Azure Monitor 用 Microsoft OpenTelemetry エクスポーター

Azure Monitor のエクスポーターを使用すると、OpenTelemetry SDK を使用してデータをエクスポートし、Python で記述されたアプリケーションのテレメトリ データを Azure Monitor に送信できます。

ソースコード | パッケージ (PyPi) | API リファレンス ドキュメント | 製品ドキュメント | サンプル | Changelog

作業の開始

パッケージをインストールする

pip を使用して Azure Monitor 用の Microsoft OpenTelemetry エクスポーターをインストールします。

pip install azure-monitor-opentelemetry-exporter --pre

前提条件

このパッケージを使用するには、次が必要です。

クライアントのインスタンス化

Azure Monitor エクスポーターとの対話は、分散トレース、ログ記録、AzureMonitorLogExporterメトリックAzureMonitorMetricExporter用の クラスのインスタンスAzureMonitorTraceExporterから始まります。 オブジェクトをインスタンス化するには 、connection_string が必要です。 接続文字列を使用してエクスポーターを構築する方法のデモについては、以下のリンク先のサンプルを参照してください。

ログ記録 (試験段階)

注: のログ信号 AzureMonitorLogExporter は、現在試験段階の状態です。 将来、破壊的変更が発生する可能性があります。

from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
exporter = AzureMonitorLogExporter(
    connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)

メトリック

from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter
exporter = AzureMonitorMetricExporter(
    connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)

トレース

from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
exporter = AzureMonitorTraceExporter(
    connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)

コンストラクターを使用してエクスポーターを直接インスタンス化することもできます。 この場合、接続文字列は環境変数から自動的にAPPLICATIONINSIGHTS_CONNECTION_STRING設定されます。

from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
exporter = AzureMonitorLogExporter()
from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter
exporter = AzureMonitorMetricExporter()
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
exporter = AzureMonitorTraceExporter()

主要な概念

Azure Monitor エクスポーターの主な概念には、次のようなものがあります。

  • OpenTelemetry: OpenTelemetry は、ソフトウェアのパフォーマンスと動作を理解するために、分析のためにテレメトリ データ (メトリック、ログ、トレース) を収集およびエクスポートするために使用されるライブラリのセットです。

  • インストルメンテーション: OpenTelemetry API を任意のアプリケーションで直接呼び出す機能は、インストルメンテーションによって容易になります。 別のライブラリの OpenTelemetry 監視を有効にするライブラリは、インストルメンテーション ライブラリと呼ばれます。

  • ログ: ログは、ログ記録、例外、およびイベントのキャプチャを指します。

  • LogRecord: サポートされているログ ライブラリから出力されるログ レコードを表します。

  • ロガー: を LogRecord 読み取り可能な LogDataに変換し、エクスポートする SDK を介してプッシュされます。

  • ロガー プロバイダー: 指定されたインストルメンテーション ライブラリの を提供 Logger します。

  • LogRecordProcessor: ログ レコード出力アクションをフックするインターフェイス。

  • LoggingHandler: 標準の Python logging ライブラリから OpenTelemetry 形式でログ 記録レコードを書き込むハンドラー クラス。

  • AzureMonitorLogExporter: これは、ログ関連のテレメトリを Azure Monitor に送信するために初期化されるクラスです。

  • メトリック: Metric 事前に定義された集計と一定期間の属性セットを使用して未加工の測定値を記録することを指します。

  • 測定: ある時点で記録されたデータ ポイントを表します。

  • インストルメント: インストルメントは、レポート Measurementに使用されます。

  • 測定: は Meter を作成する役割を Instruments担います。

  • 測定プロバイダー: 指定されたインストルメンテーション ライブラリの を提供 Meter します。

  • メトリック リーダー: 収集、フラッシュ、シャットダウンなど、OpenTelemetry Metrics SDK の一般的な構成可能な側面を提供する SDK 実装オブジェクト。

  • AzureMonitorMetricExporter: これは、メトリック関連のテレメトリを Azure Monitor に送信するために初期化されるクラスです。

  • トレース: トレースは分散トレースを参照します。 分散トレースは一連のイベントであり、1 つの論理操作の結果としてトリガーされ、アプリケーションのさまざまなコンポーネントに統合されます。 特に、トレースはスパンの有向非巡回グラフ (DAG) と考えることができます。スパン間のエッジは親/子リレーションシップとして定義されます。

  • スパン: 内の 1 つの操作を Trace表します。 入れ子にしてトレース ツリーを形成できます。 各トレースにはルート スパンが含まれています。通常は、操作全体を記述し、必要に応じて、サブ操作用に 1 つ以上のサブスパンを記述します。

  • トレーサー: を作成する必要 Spanがあります。

  • トレーサー プロバイダー: 指定されたインストルメンテーション ライブラリで使用するための を提供 Tracer します。

  • スパン プロセッサ: スパン プロセッサを使用すると、SDK の開始メソッドと終了メソッドの Span 呼び出しにフックを使用できます。 詳細については、リンクを参照してください。

  • AzureMonitorTraceExporter: これは、トレース関連のテレメトリを Azure Monitor に送信するために初期化されるクラスです。

  • サンプリング: サンプリングは、バックエンドに収集および送信されるトレースのサンプルの数を減らすことで、OpenTelemetry によって発生するノイズとオーバーヘッドを制御するメカニズムです。

  • ApplicationInsightsSampler: Application Insights SDK と Application Insights にデータを送信する OpenTelemetry ベースの SDK 全体で一貫したサンプリングに使用される Application Insights 固有のサンプラー。 このサンプラーは、必ず AzureMonitorTraceExporter 使用する必要があります。

これらのリソースの詳細については、「 Azure Monitor とは」を参照してください。

構成

すべての構成オプションは、 を介してエクスポーターのコンストラクターを介して kwargs渡すことができます。 構成可能なオプションの一覧を次に示します。

  • connection_string: Application Insights リソースに使用される接続文字列。
  • disable_offline_storage: 再試行のために失敗したテレメトリ レコードの格納を無効にするかどうかを決定するブール値。 既定値は False です。
  • storage_directory: 再試行ファイルを格納するストレージ ディレクトリ。 既定値は <tempfile.gettempdir()>/Microsoft/AzureMonitor/opentelemetry-python-<your-instrumentation-key> です。
  • credential: Azure Active Directory (AAD) 認証に使用される、ManagedIdentityCredential や ClientSecretCredential などのトークン資格情報。 既定値は None です。 例については、 サンプル を参照してください。

ログ記録 (試験段階)

注: のログ信号 AzureMonitorLogExporter は、現在試験段階の状態です。 将来、破壊的変更が発生する可能性があります。

次のセクションでは、次のような最も一般的なタスクをカバーするいくつかのコード スニペットを示します。

OpenTelemetry Logging SDK を確認して、OpenTelemetry コンポーネントを使用してログを収集する方法を確認します。

Hello World ログのエクスポート

"""
An example to show an application using Opentelemetry logging sdk. Logging calls to the standard Python
logging library are tracked and telemetry is exported to application insights with the AzureMonitorLogExporter.
"""
import os
import logging

from opentelemetry.sdk._logs import (
    LoggerProvider,
    LoggingHandler,
    set_logger_provider,
)
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor

from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter

logger_provider = LoggerProvider()
set_logger_provider(logger_provider)

exporter = AzureMonitorLogExporter(
    connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)

logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
handler = LoggingHandler()

# Attach LoggingHandler to root logger
logging.getLogger().addHandler(handler)
logging.getLogger().setLevel(logging.NOTSET)

logger = logging.getLogger(__name__)

logger.warning("Hello World!")

# Telemetry records are flushed automatically upon application exit
# If you would like to flush records manually yourself, you can call force_flush()
logger_provider.force_flush()

相関ログのエクスポート

"""
An example showing how to include context correlation information in logging telemetry.
"""
import os
import logging

from opentelemetry import trace
from opentelemetry.sdk._logs import (
    LoggerProvider,
    LoggingHandler,
    set_logger_provider,
)
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.trace import TracerProvider

from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter

trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)
logger_provider = LoggerProvider()
set_logger_provider(logger_provider)

exporter = AzureMonitorLogExporter(
    connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)

logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
handler = LoggingHandler()

# Attach LoggingHandler to root logger
logging.getLogger().addHandler(handler)
logging.getLogger().setLevel(logging.NOTSET)

logger = logging.getLogger(__name__)

logger.info("INFO: Outside of span")
with tracer.start_as_current_span("foo"):
    logger.warning("WARNING: Inside of span")
logger.error("ERROR: After span")

カスタム プロパティ ログのエクスポート

"""
An example showing how to add custom properties to logging telemetry.
"""
import os
import logging

from opentelemetry.sdk._logs import (
    LoggerProvider,
    LoggingHandler,
    set_logger_provider,
)
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor

from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter

logger_provider = LoggerProvider()
set_logger_provider(logger_provider)

exporter = AzureMonitorLogExporter(
    connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)

logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
handler = LoggingHandler()

# Attach LoggingHandler to root logger
logging.getLogger().addHandler(handler)
logging.getLogger().setLevel(logging.NOTSET)

logger = logging.getLogger(__name__)

# Custom properties
logger.debug("DEBUG: Debug with properties", extra={"debug": "true"})

例外ログのエクスポート

"""
An example showing how to export exception telemetry using the AzureMonitorLogExporter.
"""
import os
import logging

from opentelemetry._logs import (
    get_logger_provider,
    set_logger_provider,
)
from opentelemetry.sdk._logs import (
    LoggerProvider,
    LoggingHandler,
)
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor

from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter

set_logger_provider(LoggerProvider())
exporter = AzureMonitorLogExporter(
    connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(exporter))

# Attach LoggingHandler to namespaced logger
handler = LoggingHandler()
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.NOTSET)

# The following code will generate two pieces of exception telemetry
# that are identical in nature
try:
    val = 1 / 0
    print(val)
except ZeroDivisionError:
    logger.exception("Error: Division by zero")

try:
    val = 1 / 0
    print(val)
except ZeroDivisionError:
    logger.error("Error: Division by zero", stack_info=True, exc_info=True)

メトリック

次のセクションでは、次のような最も一般的なタスクをカバーするいくつかのコード スニペットを示します。

OpenTelemetry Metrics SDK を確認して、OpenTelemetry コンポーネントを使用してメトリックを収集する方法を確認します。

メトリック インストルメントの使用状況

"""
An example to show an application using all instruments in the OpenTelemetry SDK. Metrics created
and recorded using the sdk are tracked and telemetry is exported to application insights with the
AzureMonitorMetricsExporter.
"""
import os
from typing import Iterable

from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader

from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter

exporter = AzureMonitorMetricExporter(
    connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
reader = PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))

# Create a namespaced meter
meter = metrics.get_meter_provider().get_meter("sample")

# Callback functions for observable instruments
def observable_counter_func(options: CallbackOptions) -> Iterable[Observation]:
    yield Observation(1, {})


def observable_up_down_counter_func(
    options: CallbackOptions,
) -> Iterable[Observation]:
    yield Observation(-10, {})


def observable_gauge_func(options: CallbackOptions) -> Iterable[Observation]:
    yield Observation(9, {})

# Counter
counter = meter.create_counter("counter")
counter.add(1)

# Async Counter
observable_counter = meter.create_observable_counter(
    "observable_counter", [observable_counter_func]
)

# UpDownCounter
up_down_counter = meter.create_up_down_counter("up_down_counter")
up_down_counter.add(1)
up_down_counter.add(-5)

# Async UpDownCounter
observable_up_down_counter = meter.create_observable_up_down_counter(
    "observable_up_down_counter", [observable_up_down_counter_func]
)

# Histogram
histogram = meter.create_histogram("histogram")
histogram.record(99.9)

# Async Gauge
gauge = meter.create_observable_gauge("gauge", [observable_gauge_func])

# Upon application exit, one last collection is made and telemetry records are
# flushed automatically. # If you would like to flush records manually yourself,
# you can call force_flush()
meter_provider.force_flush()

メトリック カスタム ビュー

"""
This example shows how to customize the metrics that are output by the SDK using Views. Metrics created
and recorded using the sdk are tracked and telemetry is exported to application insights with the
AzureMonitorMetricsExporter.
"""
import os

from opentelemetry import metrics
from opentelemetry.sdk.metrics import Counter, MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.view import View

from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter

exporter = AzureMonitorMetricExporter.from_connection_string(
    os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
# Create a view matching the counter instrument `my.counter`
# and configure the new name `my.counter.total` for the result metrics stream
change_metric_name_view = View(
    instrument_type=Counter,
    instrument_name="my.counter",
    name="my.counter.total",
)

reader = PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
provider = MeterProvider(
    metric_readers=[
        reader,
    ],
    views=[
        change_metric_name_view,
    ],
)
metrics.set_meter_provider(provider)

meter = metrics.get_meter_provider().get_meter("view-name-change")
my_counter = meter.create_counter("my.counter")
my_counter.add(100)

メトリック Views SDK のその他の例については、 こちらを参照してください

メトリック レコード属性

"""
An example to show an application using different attributes with instruments in the OpenTelemetry SDK.
Metrics created and recorded using the sdk are tracked and telemetry is exported to application insights
with the AzureMonitorMetricsExporter.
"""
import os

from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader

from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter

exporter = AzureMonitorMetricExporter.from_connection_string(
    os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
reader = PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))

attribute_set1 = {
    "key1": "val1"
}
attribute_set2 = {
    "key2": "val2"
}
large_attribute_set = {}
for i in range(20):
    key = "key{}".format(i)
    val = "val{}".format(i)
    large_attribute_set[key] = val

meter = metrics.get_meter_provider().get_meter("sample")

# Counter
counter = meter.create_counter("attr1_counter")
counter.add(1, attribute_set1)

# Counter2
counter2 = meter.create_counter("attr2_counter")
counter2.add(10, attribute_set1)
counter2.add(30, attribute_set2)

# Counter3
counter3 = meter.create_counter("large_attr_counter")
counter3.add(100, attribute_set1)
counter3.add(200, large_attribute_set)

トレース

次のセクションでは、次のような最も一般的なタスクをカバーするいくつかのコード スニペットを示します。

OpenTelemetry トレース SDK を確認して、OpenTelemetry コンポーネントを使用してログを収集する方法を確認します。

トレースHello Worldエクスポート

"""
An example to show an application using Opentelemetry tracing api and sdk. Custom dependencies are
tracked via spans and telemetry is exported to application insights with the AzureMonitorTraceExporter.
"""
import os
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter

tracer_provider = TracerProvider()
trace.set_tracer_provider(tracer_provider)
tracer = trace.get_tracer(__name__)
# This is the exporter that sends data to Application Insights
exporter = AzureMonitorTraceExporter(
    connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
span_processor = BatchSpanProcessor(exporter)
trace.get_tracer_provider().add_span_processor(span_processor)

with tracer.start_as_current_span("hello"):
    print("Hello, World!")

# Telemetry records are flushed automatically upon application exit
# If you would like to flush records manually yourself, you can call force_flush()
tracer_provider.force_flush()

要求ライブラリを使用したインストルメンテーション

OpenTelemetry では、サードパーティのライブラリを使用してインストルメンテーションを可能にするインストルメンテーションも複数サポートされています。

OpenTelemetry で使用できるインストルメンテーションの一覧については、contrib ドキュメントを参照してください

この例では、要求ライブラリを使用してインストルメント化 する方法を 示します。

  • pip install opentelemetry-instrumentation-requests を使用して、要求インストルメンテーション パッケージをインストールします。
"""
An example to show an application instrumented with the OpenTelemetry requests instrumentation.
Calls made with the requests library will be automatically tracked and telemetry is exported to 
application insights with the AzureMonitorTraceExporter.
See more info on the requests instrumentation here:
https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-requests
"""
import os
import requests
from opentelemetry import trace
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter

# This line causes your calls made with the requests library to be tracked.
RequestsInstrumentor().instrument()

trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)
exporter = AzureMonitorTraceExporter(
    connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
span_processor = BatchSpanProcessor(exporter)
trace.get_tracer_provider().add_span_processor(span_processor)

# This request will be traced
response = requests.get(url="https://azure.microsoft.com/")

サンプリングの有効化

サンプリングを有効にして、受信するテレメトリ レコードの量を制限できます。 Application Insights で正しいサンプリングを有効にするには、次に示すように を ApplicationInsightsSampler 使用します。

"""
An example to show an application using the ApplicationInsightsSampler to enable sampling for your telemetry.
Specify a sampling rate for the sampler to limit the amount of telemetry records you receive. Custom dependencies
 are tracked via spans and telemetry is exported to application insights with the AzureMonitorTraceExporter.
"""
import os
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from azure.monitor.opentelemetry.exporter import (
    ApplicationInsightsSampler,
    AzureMonitorTraceExporter,
)

# Sampler expects a sample rate of between 0 and 1 inclusive
# A rate of 0.75 means approximately 75% of your telemetry will be sent
sampler = ApplicationInsightsSampler(0.75)
trace.set_tracer_provider(TracerProvider(sampler=sampler))
tracer = trace.get_tracer(__name__)
exporter = AzureMonitorTraceExporter(
    connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
span_processor = BatchSpanProcessor(exporter)
trace.get_tracer_provider().add_span_processor(span_processor)

for i in range(100):
    # Approximately 25% of these spans should be sampled out
    with tracer.start_as_current_span("hello"):
        print("Hello, World!")

フラッシュ/シャットダウンの動作

OpenTelemetry SDK と Azure Monitor エクスポーターを使用して設定されたすべてのアプリケーションでは、アプリケーションの終了時にテレメトリが自動的にフラッシュされます。 これは、アプリケーションが突然終了したときや、キャッチされていない例外が原因でクラッシュした場合には含まれないことに注意してください。

トラブルシューティング

エクスポーターは 、Azure Core で定義されている例外を発生させます。

次のステップ

その他のサンプル コード

一般的なシナリオを示す サンプル ディレクトリで、さらに例を見つけてください。

その他のドキュメント

Azure Monitor サービスに関するより広範なドキュメントについては、docs.microsoft.com に関する Azure Monitor のドキュメントを参照してください

OpenTelemetry の詳細な概要については、その 概要 ページを参照してください。

公式の OpenTelemetry Python ドキュメントと、その他のテレメトリ シナリオを有効にする方法については、公式の OpenTelemetry Web サイトを参照してください。

Azure Monitor でのテレメトリ シナリオを有効にする便利な事前にアセンブルされたコンポーネント (そのうちの 1 つは現在のパッケージ) のバンドルである Azure Monitor OpenTelemetry Distro の詳細については、 README を参照してください。

共同作成

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。 詳細については、 https://cla.microsoft.com を参照してください。

pull request を送信すると、CLA を提供して PR (ラベル、コメントなど) を適宜装飾する必要があるかどうかを CLA ボットが自動的に決定します。 ボットによって提供される手順にそのまま従ってください。 この操作は、Microsoft の CLA を使用するすべてのリポジトリについて、1 回だけ行う必要があります。

このプロジェクトでは、Microsoft オープン ソースの倫理規定を採用しています。 詳しくは、「Code of Conduct FAQ (倫理規定についてよくある質問)」を参照するか、opencode@microsoft.com 宛てに質問またはコメントをお送りください。