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

如何从Python Azure函数应用向Application Insights Trace表写入自定义日志?

如何将日志写入Application Insights Trace表并生成Metrics

问题根源

你当前使用OpenTelemetry的Trace Span来记录日志,这类Span数据会被Application Insights归类到Dependency表,而非目标的Trace表。要写入Trace表需使用日志API,生成Metrics则要借助专门的Metrics组件。

解决步骤及代码示例

1. 核心修改点

  • 把configure_azure_monitor移到函数外部,避免每次函数触发重复初始化
  • 用标准logging模块写日志,通过extra参数附加自定义维度
  • 用OpenTelemetry的Metrics API创建并记录指标

修改后的完整代码

import azure.functions as func
import logging
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics

# 初始化Azure Monitor,放在函数外避免重复配置
configure_azure_monitor(connection_string="你的Application Insights连接字符串")

# 获取日志记录器
logger = logging.getLogger(__name__)
# 获取Metrics Meter实例
meter = metrics.get_meter(__name__)

# 创建一个计数器指标:记录HTTP触发调用次数
http_invocation_counter = meter.create_counter(
    name="http_trigger_calls",
    description="Total number of HTTP trigger invocations",
    unit="count"
)

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

@app.route(route="http_trigger")
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
    # 写入Trace表日志,附带自定义维度
    logger.info(
        "Hello Rithwik Bojja, the logs are Logged",
        extra={"attributes": {"who": "rithwik"}}
    )

    # 记录Metrics指标,每次调用计数+1,附带维度标记端点
    http_invocation_counter.add(1, attributes={"endpoint": "/http_trigger"})

    return func.HttpResponse("This HTTP triggered function executed successfully.", status_code=200)

关键说明

  • Trace表日志:用logging.info/warn/error等方法记录的日志,会自动被导出到Application Insights的Trace表,extra={"attributes": {...}}里的内容会显示在Trace的「自定义维度」中。
  • Metrics生成:通过create_counter创建的计数器,每次调用add(1)累加数值,指标会出现在Application Insights的Metrics页面,可通过指标名http_trigger_calls查询,还能利用附加的维度做筛选。
  • 避免重复初始化:configure_azure_monitor必须放在函数外部,否则每次函数执行都会重新配置OpenTelemetry,引发数据重复或异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 00:52:20