共用方式為


適用于 Azure 監視器的 Microsoft OpenTelemetry 匯出工具

Azure 監視器的匯出工具可讓您使用 OpenTelemetry SDK 匯出資料,並將遙測資料傳送至以 Python 撰寫之應用程式的 Azure 監視器。

| 原始程式碼Package (PyPi) | API 參考檔 | 產品檔 | 樣品 | Changelog

開始使用

安裝套件

使用 pip安裝適用于 Azure 監視器的 Microsoft OpenTelemetry 匯出工具:

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

必要條件

若要使用此套件,您必須具有:

具現化用戶端

與 Azure 監視器匯出工具的互動會從類別的 AzureMonitorTraceExporter 實例開始進行分散式追蹤、 AzureMonitorLogExporter 記錄和 AzureMonitorMetricExporter 計量。 您需要 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 監視器匯出工具的一些重要概念包括:

  • OpenTelemetry:OpenTelemetry是一組程式庫,可用來收集及匯出遙測資料 (計量、記錄和追蹤,) 進行分析,以瞭解軟體的效能和行為。

  • 檢測:檢測可協助任何應用程式直接呼叫 OpenTelemetry API。 為另一個程式庫啟用 OpenTelemetry 可觀察性的程式庫稱為檢測程式庫。

  • 記錄:記錄是指擷取記錄、例外狀況和事件。

  • LogRecord:代表從支援的記錄程式庫發出的記錄檔記錄。

  • 記錄器:將 LogRecord 轉換成可 LogData 讀取的 ,並會透過要匯出的 SDK 推送。

  • 記錄器提供者:提供 Logger 指定檢測程式庫的 。

  • LogRecordProcessor:連結記錄發出動作的介面。

  • LoggingHandler:處理常式類別,會從標準 Python logging 程式庫以 OpenTelemetry 格式寫入記錄。

  • AzureMonitorLogExporter:這是初始化以將記錄相關遙測傳送至 Azure 監視器的類別。

  • 計量Metric 是指使用預先定義的匯總和一組屬性來記錄原始度量,以及一段時間的屬性集。

  • 度量:代表記錄在某個時間點的資料點。

  • 檢測:檢測是用來報告 Measurement 的。

  • 計量Meter 負責建立 Instruments

  • 計量提供者:提供 Meter 指定檢測程式庫的 。

  • 計量讀取器:SDK 實作物件,提供 OpenTelemetry Metrics SDK 的常見可設定層面,例如集合、排清和關機。

  • AzureMonitorMetricExporter:這是初始化以將計量相關遙測傳送至 Azure 監視器的類別。

  • 追蹤:追蹤是指分散式追蹤。 分散式追蹤是一組事件,會因為單一邏輯作業而觸發,併合並到應用程式的各種元件。 特別是,追蹤可以視為 Spans (DAG) 的有向無循環圖表形,其中 Span 之間的邊緣會定義為父系/子系關聯性。

  • 範圍:表示 內的 Trace 單一作業。 可以是巢狀結構,以形成追蹤樹狀結構。 每個追蹤都包含根範圍,通常描述整個作業,並選擇性地描述其子作業的一個或多個子範圍。

  • 追蹤:負責建立 Span

  • 追蹤提供者:提供 Tracer 供指定檢測程式庫使用的 。

  • 範圍處理器:範圍處理器允許 SDK 的 Span 開始和結束方法調用攔截。 如需詳細資訊,請遵循連結。

  • AzureMonitorTraceExporter:這是初始化以將追蹤相關遙測傳送至 Azure 監視器的類別。

  • 取樣:取樣是一種機制,可藉由減少收集並傳送至後端的追蹤樣本數目,來控制 OpenTelemetry 所導入的雜訊和額外負荷。

  • ApplicationInsightsSampler:Application Insights 特定的取樣器,用於跨 Application Insights SDK 和 OpenTelemetry 型 SDK 將資料傳送至 Application Insights 的一致取樣。 每當 AzureMonitorTraceExporter 使用時,都必須使用此取樣器。

如需這些資源的詳細資訊,請參閱 什麼是 Azure 監視器?

設定

所有組態選項都可以透過 透過 傳遞匯出工具的建構函式。 kwargs 以下是可設定的選項清單。

  • connection_string:用於 Application Insights 資源的連接字串。
  • disable_offline_storage:布林值,判斷是否要停用儲存失敗的遙測記錄以進行重試。 預設值為 False
  • storage_directory:用來儲存重試檔案的儲存體目錄。 預設值為 <tempfile.gettempdir()>/Microsoft/AzureMonitor/opentelemetry-python-<your-instrumentation-key>
  • credential:權杖認證,例如 ManagedIdentityCredential 或 ClientSecretCredential,用於 Azure Active Directory (AAD) 驗證。 預設為 [無]。 如需 範例 ,請參閱範例。

範例

記錄 (實驗性)

注意:的 AzureMonitorLogExporter 記錄訊號目前處於實驗性狀態。 未來可能會發生重大變更。

下列各節提供數個程式碼片段,涵蓋一些最常見的工作,包括:

檢閱 OpenTelemetry 記錄 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 計量 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)

您可以在這裡找到更多計量 SDK 的 Views 範例。

計量記錄屬性

"""
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 安裝 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 監視器匯出工具設定的所有應用程式,遙測會在應用程式結束時自動排清。 請注意,當應用程式因未攔截的例外狀況而突然結束或當機時,不會包含此功能。

疑難排解

匯出工具會引發 Azure Core中定義的例外狀況。

下一步

更多的程式碼範例

請在示範常見案例的 範例 目錄中尋找進一步的範例。

其他文件

如需有關 Azure 監視器服務的詳細資訊檔,請參閱有關 docs.microsoft.com 的 Azure 監視器檔

如需 OpenTelemetry 的詳細概觀,請流覽其 概觀 頁面。

如需官方 OpenTelemetry Python 檔以及如何啟用其他遙測案例,請流覽官方 OpenTelemetry 網站

如需 Azure 監視器 OpenTelemetry 散發版本的詳細資訊,這是一組實用的預先組合元件, (其中一個元件是這個目前套件) ,可透過 Azure 監視器啟用遙測案例,請造訪 README

參與

此專案歡迎參與和提供建議。 大部分的參與都要求您同意「參與者授權合約 (CLA)」,宣告您有權且確實授與我們使用投稿的權利。 如需詳細資料,請前往 https://cla.microsoft.com

當您提交提取要求時,CLA Bot 會自動判斷您是否需要提供 CLA,並適當地裝飾 PR (例如標籤、註解)。 請遵循 bot 提供的指示。 您只需要使用我們的 CLA 在所有存放庫上執行此動作一次。

此專案採用 Microsoft Open Source Code of Conduct (Microsoft 開放原始碼管理辦法)。 如需詳細資訊,請參閱管理辦法常見問題集,如有任何其他問題或意見請連絡 opencode@microsoft.com