You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Azure Monitor Metric Exporter(Python)推送OpenTelemetry指标至Azure App Insights

解决OpenTelemetry指标推送到Azure Application Insights的问题

一、配置OpenTelemetry指标导出器

要推送指标,你需要新增AzureMonitorMetricExporter(和你已用的AzureMonitorTraceExporter并行使用),以下是核心配置步骤(以Python为例,其他语言逻辑一致):

  • 安装依赖:pip install opentelemetry-exporter-azure-monitor
  • 初始化指标导出器与提供者:
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.exporter.azuremonitor import AzureMonitorMetricExporter

# 用App Insights连接字符串初始化导出器
exporter = AzureMonitorMetricExporter.from_connection_string(
    "YOUR_APP_INSIGHTS_CONNECTION_STRING"
)

# 创建定期导出的指标读取器(默认60秒导出一次)
reader = PeriodicExportingMetricReader(exporter)
provider = MeterProvider(metric_readers=[reader])
metrics.set_meter_provider(provider)

# 获取用于创建指标的meter实例
meter = metrics.get_meter("your-app-metric-meter")

二、自定义指标实现示例

1. 函数执行耗时(直方图类型)

直方图适合记录耗时,方便后续统计平均耗时、分位数等维度:

import time

# 定义耗时指标
function_duration_histogram = meter.create_histogram(
    name="function.execution.duration",
    description="Function execution duration in milliseconds",
    unit="ms"
)

def target_function():
    start = time.time()
    # 这里替换为你的函数业务逻辑
    time.sleep(0.3)
    duration_ms = (time.time() - start) * 1000
    # 记录指标,可添加函数名等属性用于筛选
    function_duration_histogram.record(
        duration_ms,
        attributes={"function_name": "target_function"}
    )

2. 内存占用(仪表类型)

仪表适合记录实时数值,比如进程当前内存占用:

import os
import psutil

# 定义内存指标
memory_gauge = meter.create_gauge(
    name="process.memory.usage",
    description="Current process memory usage in MB",
    unit="MB"
)

def track_memory():
    process = psutil.Process(os.getpid())
    mem_mb = process.memory_info().rss / (1024 * 1024)
    memory_gauge.record(
        mem_mb,
        attributes={"process_id": os.getpid()}
    )

三、指标在Application Insights中的查询位置

推送成功后,自定义指标会统一存储在**customMetrics表**中,你可以通过Azure Monitor的Log Analytics查询:

  • 查询所有自定义指标:
customMetrics
| where name in ("function.execution.duration", "process.memory.usage")
| project timestamp, name, value, valueUnit, customDimensions
  • 按小时统计指定函数的平均耗时:
customMetrics
| where name == "function.execution.duration" and customDimensions.function_name == "target_function"
| summarize avg(value) by bin(timestamp, 1h)

如果是OTEL自动采集的系统级指标(如CPU使用率),部分会出现在performanceCounters表,但你自定义的函数耗时、内存占用这类指标只会在customMetrics中。

四、常见排查点

  • 确认App Insights连接字符串拥有Metrics写入权限
  • 检查指标导出器与追踪导出器的Provider是否兼容(避免重复设置全局Provider)
  • 查看OTEL运行日志,确认指标是否被正常生成并触发导出
  • 指标导出有延迟(默认60秒一次),推送后需等待几分钟再去Log Analytics查询

内容的提问来源于stack exchange,提问作者Kulasangar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:12:40