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

Azure Monitor OpenTelemetry Python脚本无日志输出问题求助

问题

参考Azure SDK for Python示例编写了Python脚本,通过Azure Monitor OpenTelemetry将日志发送到Application Insights。已执行azd auth login完成认证,脚本运行无报错,但Application Insights中始终没有日志数据显示,且确认拥有对应资源的访问权限。脚本代码如下:

import logging
from azure.monitor.opentelemetry import configure_azure_monitor
from azure.identity import DefaultAzureCredential
from opentelemetry import metrics

large_attribute_set = {}
for i in range(20):
    key = "key{}".format(i)
    val = "val{}".format(i)
    large_attribute_set[key] = val

credential = DefaultAzureCredential()

configure_azure_monitor(
    logger_name=__name__,
    credential=credential,
    connection_string="InstrumentationKey=xx-xx-xx-xx-xx;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/;LiveEndpoint=https://westeurope.livediagnostics.monitor.azure.com/;ApplicationId=x-x-x-x-x",
    )

logger = logging.getLogger(__name__)

meter = metrics.get_meter_provider().get_meter("sample")
counter = meter.create_counter("my_counter")
counter.add(1)

logger.info("info1", extra=large_attribute_set)
logger.warning("warning1", extra=large_attribute_set)
logger.error("error1", extra=large_attribute_set)
logger.critical("critical1", extra=large_attribute_set)
排查方案
  • 移除冲突的认证配置:configure_azure_monitor中同时传入credential和connection_string会导致冲突。connection_string本身已包含InstrumentationKey,无需额外提供DefaultAzureCredential,直接删除credential=credential参数即可。修改后的配置:

    configure_azure_monitor(
        logger_name=__name__,
        connection_string="InstrumentationKey=xx-xx-xx-xx-xx;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/;LiveEndpoint=https://westeurope.livediagnostics.monitor.azure.com/;ApplicationId=x-x-x-x-x",
    )
    
  • 调整日志级别:默认情况下,Python logging模块的级别为WARNING,这会导致info级别的日志被过滤。需要显式设置logger的级别为INFO或更低,确保所有日志都能被捕获:

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)  # 添加这行
    
  • 等待导出器完成发送:OpenTelemetry的日志导出器默认采用批量发送机制,脚本执行完毕后可能还没完成数据上传就退出了。在脚本末尾添加延迟,给导出器足够的时间发送数据:

    import time
    time.sleep(5)  # 等待5秒后再结束脚本
    
  • 减少属性数量测试:Azure Monitor对单条日志的属性数量有限制(默认最多10个自定义属性),你当前传入了20个属性,可能导致日志被丢弃。先将属性数量减少到10个以内,验证是否能正常发送。

  • 启用调试日志排查:添加调试日志,查看SDK内部的发送状态,定位是否有错误发生:

    # 在脚本最顶部添加
    logging.basicConfig(level=logging.DEBUG)
    

    运行脚本后查看控制台输出,若有导出失败的信息,可根据错误提示进一步排查。

内容的提问来源于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.14 13:18:25