opentelemetry 显式添加指标 - azure monitor - opentelemetry

opentelemetry add metrics explicitly - azure monitor - opentelemetry

我想在 ms azure monitor (application insights) 中跟踪某些 id 的使用。我目前正在使用以下代码摘录来执行此操作。问题是,例如,如果快速连续拨打六个电话,则第一个电话会被跟踪六次。第二个被跟踪了五次。第三次四次等等。 (看下图)如何解决所有id只在显式调用时才被跟踪?

from azure_monitor import AzureMonitorMetricsExporter
from opentelemetry import metrics
from opentelemetry.sdk.metrics import Counter, MeterProvider
from opentelemetry.sdk.metrics.export.controller import PushController

metrics.set_meter_provider(MeterProvider())
meter = metrics.get_meter(__name__)
exporter = AzureMonitorMetricsExporter(
    connection_string='InstrumentationKey=<my-key>'
)
controller = PushController(meter, exporter, 0)


def add_question(question_id):
    requests_counter = meter.create_metric(
        name=question_id,
        description="question used",
        unit="1",
        value_type=int,
        metric_type=Counter,
    )
    labels = {"type": "question"}
    requests_counter.add(1, labels)
    controller.shutdown()
    print(str(datetime.now()) + " - Done recording metric: question")
    print(question_id)

我的问题已通过对我的 github 错误报告的评论解决。唯一要做的更改是将 statefull=False 添加到 MeterProvider,如下所示:

metrics.set_meter_provider(MeterProvider(stateful=False))