首页 > 解决方案 > 如何使用 OpenCensus 发送指标

问题描述

我正在尝试使用 OpenCensus 和 Azure Application Insights 在 Python 中发送指标。

理想情况下,我想发送一些具有任意结构的 Python 字典,但是 OpenCensus 似乎“自动侦听日志记录/打印语句”,但是当我搜索这些内容时,我在 Azure 门户上没有看到任何证据。

OpenCensusprint(...)有什么特别之处吗?这如何捕获打印语句的内容?

我尝试了 2 种不同的方法(代码见下文):

AFAIK作为原则:

我想了解:


import json
import psutil

from opencensus.trace.samplers import AlwaysOnSampler
from opencensus.trace.tracer import Tracer

from opencensus.ext.azure import metrics_exporter
from opencensus.ext.azure.trace_exporter import AzureExporter

if __name__ == "__main__":
    # loading the instrumentation key (for the Azure Application Insights app) from a JSON file
    azure_conf = json.loads(open("tf/ai_details.json", 'r').read())
    ai_instrumentation_key = azure_conf['instrumentation_key']['value']
    # print(ai_instrumentation_key)

    # test 1: trying to "send a metric", does that mean that the metric exporter listens to "print(...)"?
    _me = metrics_exporter.new_metrics_exporter(connection_string='InstrumentationKey={}'.format(ai_instrumentation_key))
    print(psutil.virtual_memory())
    print("Done recording metrics")

    # test 2: trying to "send a metric", how can I make the "span" to send a dictionary?
    azure_exporter = AzureExporter(connection_string='InstrumentationKey={}'.format(ai_instrumentation_key))
    # https://opencensus.io/api/python/trace/api/tracer.html
    tracer = Tracer(exporter=azure_exporter, sampler=AlwaysOnSampler())
    # https://opencensus.io/api/python/trace/api/span.html#opencensus.trace.span.Span
    with tracer.span(name='TestSpan') as span:
        print('Hello, World!') # is the span only listening to "print(...)"?
        span.add_attribute("foo-span-key", "foo-span-value") # this does not seem to do anything

标签: pythonazure-application-insightsazure-log-analyticsopencensus

解决方案


感谢您将 OpenCensus 与 Azure Monitor 一起使用!你可以在线找到我的答案。

如何在 OpenCensus 中将任意字典作为“指标”发送?将应用程序用于 Application Insights 时,这将如何显示在 Azure 门户上?

任意字典是什么意思?在您的代码片段中,您似乎希望将单个数据点作为指标数据发送到 Azure Monitor 后端 (Application Insights)。有关如何开始使用 OpenCensus 的步骤,请查看 Microsoft 网站上的概述页面。这将向您展示如何使用 OpenCensus 正确检测您的应用程序,以及如何将遥测数据发送到 Azure Monitor。如果您仍然对如何检测您的应用程序以满足您的业务用例感到困惑,那么您可以查看以下更多示例

OpenCensus 中的 print(...)(或 logging.info(...))和 HTTP 请求有什么特别之处?这些信息应该如何在 Application Insights 应用程序中的 Azure 门户上有用?

print命令在 OpenCensus 中没有特殊含义。对于日志,如果您使用 OpenCensus Azure Monitor 进行检测并使用日志导出器,则可以从 Python 标准日志库自动发送日志遥测。对于 HTTP 请求,您可以使用跟踪导出器和各种 OpenCensus 库集成来跟踪传入请求传出请求,具体取决于您要跟踪遥测的库。

以上内容是否与跟踪器/跨度无关,或者在需要发送度量时必须使用跨度?

跨度是仅用于跟踪(使用 AzureExporter)的概念。您无需创建跨度来发送指标数据(指标导出器)。查看上面的链接,了解如何使用其中的每一个。


推荐阅读