你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
适用于 Azure Monitor 的 Microsoft OpenTelemetry 导出程序
Azure Monitor 的导出器允许你利用 OpenTelemetry SDK 导出数据,并将遥测数据发送到 Azure Monitor 以用于使用 Python 编写的应用程序。
源代码 | 包 (PyPi) | API 参考文档 | 产品文档 | 样品 | 更改日志
入门
安装包
使用 pip 安装适用于 Azure Monitor 的 Microsoft OpenTelemetry 导出程序:
pip install azure-monitor-opentelemetry-exporter --pre
先决条件
若要使用此包,必须具有:
- Azure 订阅 - 创建免费帐户
- Azure Monitor - 如何使用应用程序见解
- OpenTelemetry SDK - 适用于 Python 的 OpenTelemetry SDK
- Python 3.7 或更高版本 - 安装 Python
对客户端进行实例化
与 Azure Monitor 导出程序交互从 类的 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 Monitor 导出程序的某些关键概念包括:
OpenTelemetry:OpenTelemetry 是一组库,用于收集和导出遥测数据, (指标、日志和跟踪) 进行分析,以了解软件的性能和行为。
检测:通过检测,任何应用程序直接调用 OpenTelemetry API 的功能都得到了促进。 为另一个库启用 OpenTelemetry 可观测性的库称为检测库。
日志:日志是指捕获日志记录、异常和事件。
LogRecord:表示从支持的日志记录库发出的日志记录。
记录器:将
LogRecord
转换为可读 的LogData
,并将通过要导出的 SDK 推送。记录器提供程序:为给定的检测库提供
Logger
。LogRecordProcessor:用于挂钩日志记录发出操作的接口。
LoggingHandler:一个处理程序类,用于从标准 Python
logging
库以 OpenTelemetry 格式写入日志记录记录。AzureMonitorLogExporter:这是初始化的类,用于向 Azure Monitor 发送与日志记录相关的遥测数据。
指标:
Metric
指记录一段时间内具有预定义聚合和属性集的原始度量值。度量:表示在某个时间点记录的数据点。
仪器:仪器用于报告
Measurement
。计量:
Meter
负责创建Instruments
。计量提供程序:为给定的检测库提供
Meter
。指标读取器:一个 SDK 实现对象,提供 OpenTelemetry 指标 SDK 的常见可配置方面,例如收集、刷新和关闭。
AzureMonitorMetricExporter:这是初始化的类,用于将指标相关的遥测数据发送到 Azure Monitor。
跟踪:跟踪是指分布式跟踪。 分布式跟踪是一组事件,由单个逻辑操作触发,跨应用程序的各个组件进行合并。 具体而言,跟踪可以视为一个有向无环图, (DAG) 范围,其中 Span 之间的边缘定义为父/子关系。
Span:表示 中的单个
Trace
操作。 可以嵌套以形成跟踪树。 每个跟踪都包含一个根范围,该根范围通常描述整个操作,并且可以选择描述其子操作的一个或多个子范围。跟踪器:负责创建
Span
。跟踪器提供程序:提供供
Tracer
给定检测库使用的 。范围处理器:范围处理器允许对 SDK 的
Span
开始和结束方法调用使用挂钩。 有关详细信息,请参阅链接。AzureMonitorTraceExporter:这是初始化的类,用于将跟踪相关的遥测数据发送到 Azure Monitor。
采样:采样是一种通过减少收集并发送到后端的跟踪样本数来控制 OpenTelemetry 引入的干扰和开销的机制。
ApplicationInsightsSampler:特定于 Application Insights 的采样器,用于跨 Application Insights SDK 和基于 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 日志记录 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)
可在此处找到指标 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 安装 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 网站。
有关 Azure Monitor OpenTelemetry 发行版的详细信息,它是一系列有用的预组装组件, (其中一个是当前包) ,用于通过 Azure Monitor 启用遥测方案,请访问 README。
贡献
本项目欢迎贡献和建议。 大多数贡献要求你同意贡献者许可协议 (CLA),并声明你有权(并且确实有权)授予我们使用你的贡献的权利。 有关详细信息,请访问 https://cla.microsoft.com 。
提交拉取请求时,CLA 机器人将自动确定你是否需要提供 CLA,并相应地修饰 PR(例如标签、注释)。 直接按机器人提供的说明操作。 只需使用 CLA 对所有存储库执行一次这样的操作。
此项目采用了 Microsoft 开放源代码行为准则。 有关详细信息,请参阅行为准则常见问题解答,或如果有任何其他问题或意见,请与 联系。