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

Azure Functions集成OpenTelemetry后日志刷屏与重复问题求助

Azure Functions集成OpenTelemetry日志问题解决

一、自定义日志重复问题解决

重复日志源于configure_azure_monitor()默认捕获所有日志(含Azure Functions原生日志),同时平台自身日志系统也会输出内容。可通过以下两种方式处理:

方式1:过滤OTel捕获的原生日志

自定义日志处理器,过滤掉Azure Functions原生的azure.functions日志:

import azure.functions as func
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry.sdk._logs import LogProcessor, LogRecord
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter

class CustomLogFilter(LogProcessor):
    def __init__(self, next_processor):
        self.next_processor = next_processor

    def on_start(self, log_record):
        # 仅保留非azure.functions命名空间的日志
        if log_record.logger_name != "azure.functions":
            self.next_processor.on_start(log_record)

    def on_end(self, log_record):
        if log_record.logger_name != "azure.functions":
            self.next_processor.on_end(log_record)

    def shutdown(self):
        self.next_processor.shutdown()

def configure_custom_monitor():
    exporter = AzureMonitorLogExporter()
    batch_processor = BatchLogRecordProcessor(exporter)
    filtered_processor = CustomLogFilter(batch_processor)
    configure_azure_monitor(log_processors=[filtered_processor])

configure_custom_monitor()

app = func.FunctionApp()
app.register_blueprint(cve.bp)
app.register_blueprint(ddc2.bp)
app.register_blueprint(ddc3.bp)

方式2:禁用OTel自动日志捕获

设置环境变量关闭OTel自动捕获所有日志,仅通过自定义logger输出带维度的日志:

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

# 关闭OTel自动捕获全局日志
os.environ["OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED"] = "false"

configure_azure_monitor()

# 创建自定义日志实例,用于输出带自定义维度的日志
custom_logger = logging.getLogger("my_business_logger")

# 函数内使用示例:
# custom_logger.info("订单处理完成", extra={"order_id": "ORD_20240501", "status": "success"})

app = func.FunctionApp()
app.register_blueprint(cve.bp)
app.register_blueprint(ddc2.bp)
app.register_blueprint(ddc3.bp)

二、每3秒大量无用日志问题解决

这类日志多为OTel内部调试日志或平台心跳日志,可通过以下配置处理:

  • 调整OTel日志级别:设置环境变量OTEL_LOG_LEVEL=WARNING,仅输出警告及以上级别的日志,过滤调试类冗余内容。
  • 禁用不需要的OTel组件:如果不需要分布式追踪或指标采集,可通过环境变量关闭:
    • OTEL_TRACES_EXPORTER=none
    • OTEL_METRICS_EXPORTER=none
  • 过滤平台心跳日志:如果是Azure Functions的健康检查日志,可在Application Insights的日志查询中添加过滤规则,排除特定关键词的日志条目。

额外提示

  • 确保azure-monitor-opentelemetry包为最新版本,旧版本可能存在日志冗余或重复的已知问题。
  • 自定义维度需通过extra参数传递给logger,OTel会自动将其作为自定义属性同步到Application Insights。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:13:14