You need to enable JavaScript to run this app. 如何在Opentelemetry中忽略指定的Flask路由链路追踪
优惠活动
大模型
产品
解决方案
定价
更多

如何在Opentelemetry中忽略指定的Flask路由链路追踪

Flask OpenTelemetry 冗余端点过滤实现方案

方案1:使用内置excluded_urls参数(无侵入,优先选择)

opentelemetry-instrumentation-flask 原生提供专门的端点过滤参数,无需额外编写业务逻辑,有两种使用方式:

  • 代码埋点场景直接传入参数
from opentelemetry.instrumentation.flask import FlaskInstrumentor

# 多个过滤路径用逗号分隔,支持*通配符匹配路径规则
FlaskInstrumentor().instrument_app(
    app,
    excluded_urls="/health,/healthz,/ready,/static/*"
)
  • 自动埋点场景(使用opentelemetry-instrument命令启动应用)无需修改代码,直接配置对应环境变量即可:
export OTEL_PYTHON_FLASK_EXCLUDED_URLS="/health,/healthz,/static/*"
opentelemetry-instrument python your_flask_app.py

方案2:自定义请求钩子过滤(适合复杂过滤规则)

如果需要根据请求方法、请求头、用户标识等自定义规则过滤链路,可以通过Flask前置钩子手动控制链路采样:

from opentelemetry import trace
from flask import request

@app.before_request
def disable_trace_for_ignored_endpoints():
    # 自定义过滤规则,可按需扩展判断逻辑
    ignored_paths = {"/health", "/healthz", "/ready"}
    # 示例扩展规则:同时过滤所有OPTIONS预检请求
    if request.path in ignored_paths or request.method == "OPTIONS":
        current_span = trace.get_current_span()
        if current_span.is_recording():
            # 标记当前链路不采样,不会生成上报数据
            current_span.set_attribute("sampling.priority", 0)

效果验证

配置完成后调用过滤的端点,Elastic APM服务端将不会收到对应链路的上报数据,业务接口的链路追踪逻辑不受任何影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 04:12:01