跳转到主要内容

OpenCensus Azure Monitor 导出器

项目描述

OpenCensus Azure Monitor导出器即将被弃用。它们将于2024年9月正式停止支持。请迁移到Azure Monitor OpenTelemetry Distro,这是推荐的“一站式”解决方案,或者迁移到基于OpenTelemetry的更手动、可配置的解决方案Azure Monitor OpenTelemetry导出器。查看迁移指南以了解如何轻松迁移Python代码。

pypi

安装

pip install opencensus-ext-azure

先决条件

  • 创建一个Azure Monitor资源并获取仪器密钥,更多信息可以在官方文档中找到。

  • 将您的仪器密钥放在一个连接字符串中,并直接放入您的代码中。

  • 或者,您可以在环境变量APPLICATIONINSIGHTS_CONNECTION_STRING中指定您的连接字符串

使用

日志

Azure Monitor日志处理程序允许您将Python日志导出到Azure Monitor

以下示例展示了如何将警告级别的日志发送到Azure Monitor。

import logging

from opencensus.ext.azure.log_exporter import AzureLogHandler

logger = logging.getLogger(__name__)
logger.addHandler(AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>'))
logger.warning('Hello, World!')

关联

您可以通过使用日志集成来使用跟踪ID和跨度ID丰富日志。

import logging

from opencensus.ext.azure.log_exporter import AzureLogHandler
from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace import config_integration
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer

config_integration.trace_integrations(['logging'])

logger = logging.getLogger(__name__)

handler = AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>')
handler.setFormatter(logging.Formatter('%(traceId)s %(spanId)s %(message)s'))
logger.addHandler(handler)

tracer = Tracer(
    exporter=AzureExporter(connection_string='InstrumentationKey=<your-instrumentation_key-here>'),
    sampler=ProbabilitySampler(1.0)
)

logger.warning('Before the span')
with tracer.span(name='test'):
    logger.warning('In the span')
logger.warning('After the span')

自定义属性

您还可以使用自定义维度字段通过extra关键字参数将自定义属性添加到您的日志消息中。

警告:要使用此功能,您需要将字典传递给自定义维度字段。如果您传递其他类型的参数,则记录器将忽略它们。

import logging

from opencensus.ext.azure.log_exporter import AzureLogHandler

logger = logging.getLogger(__name__)
logger.addHandler(AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>'))

properties = {'custom_dimensions': {'key_1': 'value_1', 'key_2': 'value_2'}}
logger.warning('action', extra=properties)

修改日志

  • 您可以将回调函数传递给导出器以在导出之前处理遥测数据。

  • 如果不需要导出此信封,则您的回调函数可以返回False

  • 您的回调函数必须接受一个信封数据类型作为其参数。

  • 您可以在此处查看Azure Monitor数据类型的模式。

  • AzureLogHandler处理ExceptionDataMessageData数据类型。

import logging

from opencensus.ext.azure.log_exporter import AzureLogHandler

logger = logging.getLogger(__name__)

# Callback function to append '_hello' to each log message telemetry
def callback_function(envelope):
    envelope.data.baseData.message += '_hello'
    return True

handler = AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>')
handler.add_telemetry_processor(callback_function)
logger.addHandler(handler)
logger.warning('Hello, World!')

事件

您可以通过使用AzureEventHandler而不是trace遥测数据的方式发送customEvent遥测数据。

import logging

from opencensus.ext.azure.log_exporter import AzureEventHandler

logger = logging.getLogger(__name__)
logger.addHandler(AzureEventHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>'))
logger.setLevel(logging.INFO)
logger.info('Hello, World!')

指标

Azure Monitor指标导出器允许您将指标导出到Azure Monitor

from opencensus.ext.azure import metrics_exporter
from opencensus.stats import aggregation as aggregation_module
from opencensus.stats import measure as measure_module
from opencensus.stats import stats as stats_module
from opencensus.stats import view as view_module
from opencensus.tags import tag_map as tag_map_module

stats = stats_module.stats
view_manager = stats.view_manager
stats_recorder = stats.stats_recorder

CARROTS_MEASURE = measure_module.MeasureInt("carrots",
                                            "number of carrots",
                                            "carrots")
CARROTS_VIEW = view_module.View("carrots_view",
                                "number of carrots",
                                [],
                                CARROTS_MEASURE,
                                aggregation_module.CountAggregation())

def main():
    # Enable metrics
    # Set the interval in seconds to 60s, which is the time interval application insights
    # aggregates your metrics
    exporter = metrics_exporter.new_metrics_exporter(
        connection_string='InstrumentationKey=<your-instrumentation-key-here>'
    )
    view_manager.register_exporter(exporter)

    view_manager.register_view(CARROTS_VIEW)
    mmap = stats_recorder.new_measurement_map()
    tmap = tag_map_module.TagMap()

    mmap.measure_int_put(CARROTS_MEASURE, 1000)
    mmap.record(tmap)

    print("Done recording metrics")

if __name__ == "__main__":
    main()

性能计数器

导出器还包括一组默认导出到Azure Monitor的性能计数器。

import psutil
import time

from opencensus.ext.azure import metrics_exporter

def main():
    # Performance counters are sent by default. You can disable performance counters by
    # passing in enable_standard_metrics=False into the constructor of
    # new_metrics_exporter()
    _exporter = metrics_exporter.new_metrics_exporter(
        connection_string='InstrumentationKey=<your-instrumentation-key-here>',
        export_interval=60,
    )

    for i in range(100):
        print(psutil.virtual_memory())
        time.sleep(5)

    print("Done recording metrics")

if __name__ == "__main__":
    main()

以下是当前可用的性能计数器列表

  • 可用内存(字节)

  • CPU处理器时间(百分比)

  • 传入请求率(每秒)

  • 传入请求平均执行时间(毫秒)

  • 进程CPU使用率(百分比)

  • 进程私有字节(字节)

修改指标

  • 您可以将回调函数传递给导出器以在导出之前处理遥测数据。

  • 如果不需要导出此信封,则您的回调函数可以返回False

  • 您的回调函数必须接受一个信封数据类型作为其参数。

  • 您可以在此处查看Azure Monitor数据类型的模式。

  • MetricsExporter处理MetricData数据类型。

from opencensus.ext.azure import metrics_exporter
from opencensus.stats import aggregation as aggregation_module
from opencensus.stats import measure as measure_module
from opencensus.stats import stats as stats_module
from opencensus.stats import view as view_module
from opencensus.tags import tag_map as tag_map_module

stats = stats_module.stats
view_manager = stats.view_manager
stats_recorder = stats.stats_recorder

CARROTS_MEASURE = measure_module.MeasureInt("carrots",
                                            "number of carrots",
                                            "carrots")
CARROTS_VIEW = view_module.View("carrots_view",
                                "number of carrots",
                                [],
                                CARROTS_MEASURE,
                                aggregation_module.CountAggregation())

# Callback function to only export the metric if value is greater than 0
def callback_function(envelope):
    return envelope.data.baseData.metrics[0].value > 0

def main():
    # Enable metrics
    # Set the interval in seconds to 60s, which is the time interval application insights
    # aggregates your metrics
    exporter = metrics_exporter.new_metrics_exporter(
        connection_string='InstrumentationKey=<your-instrumentation-key-here>',
        export_interval=60,
    )
    exporter.add_telemetry_processor(callback_function)
    view_manager.register_exporter(exporter)

    view_manager.register_view(CARROTS_VIEW)
    mmap = stats_recorder.new_measurement_map()
    tmap = tag_map_module.TagMap()

    mmap.measure_int_put(CARROTS_MEASURE, 1000)
    mmap.record(tmap)

    print("Done recording metrics")

if __name__ == "__main__":
    main()

跟踪

Azure Monitor跟踪导出器允许您将OpenCensus跟踪导出到Azure Monitor

以下示例展示了如何将跨度“hello”发送到Azure Monitor。

from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer

tracer = Tracer(
    exporter=AzureExporter(
        connection_string='InstrumentationKey=<your-instrumentation-key-here>'
    ),
    sampler=ProbabilitySampler(1.0)
)

with tracer.span(name='hello'):
    print('Hello, World!')

集成

OpenCensus 还支持多种 集成,允许 OpenCensus 与第三方库集成。

此示例演示了如何与 requests 库集成。

import requests

from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace import config_integration
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer

config_integration.trace_integrations(['requests'])
tracer = Tracer(
    exporter=AzureExporter(
        connection_string='InstrumentationKey=<your-instrumentation-key-here>',
    ),
    sampler=ProbabilitySampler(1.0),
)
with tracer.span(name='parent'):
    response = requests.get(url='https://www.wikipedia.org/wiki/Rabbit')

修改追踪

  • 您可以将回调函数传递给导出器以在导出之前处理遥测数据。

  • 如果不需要导出此信封,则您的回调函数可以返回False

  • 您的回调函数必须接受一个信封数据类型作为其参数。

  • 您可以在此处查看Azure Monitor数据类型的模式。

  • AzureExporter 处理 Data 数据类型。

import requests

from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace import config_integration
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer

config_integration.trace_integrations(['requests'])

# Callback function to add os_type: linux to span properties
def callback_function(envelope):
    envelope.data.baseData.properties['os_type'] = 'linux'
    return True

exporter = AzureExporter(
    connection_string='InstrumentationKey=<your-instrumentation-key-here>'
)
exporter.add_telemetry_processor(callback_function)
tracer = Tracer(exporter=exporter, sampler=ProbabilitySampler(1.0))
with tracer.span(name='parent'):
    response = requests.get(url='https://www.wikipedia.org/wiki/Rabbit')

与 Azure Functions 集成

希望捕获 Azure Functions 环境中的自定义遥测数据的用户应使用 OpenCensus Python Azure Functions 扩展。更多详细信息请参阅此 文档

参考资料

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源分布

opencensus-ext-azure-1.1.13.tar.gz (32.7 kB 查看哈希)

上传时间

构建分布

opencensus_ext_azure-1.1.13-py2.py3-none-any.whl (43.4 kB 查看哈希)

上传时间 Python 2 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面