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

Sentry traces_sampler在FastAPI中如何针对特定路由设置采样率?

FastAPI 中 Sentry 针对特定路由设置采样率

在FastAPI集成Sentry的场景下,sampling_context字典中会包含当前请求的request对象,你可以通过它获取路由信息,进而为不同路由设置差异化的采样率。以下是带类型提示的实现示例:

from typing import Dict, Any
from fastapi import Request
import sentry_sdk

def traces_sampler(sampling_context: Dict[str, Any]) -> float:
    # 从采样上下文提取FastAPI请求对象
    request: Request = sampling_context.get("request")
    
    # 处理非HTTP请求场景(如后台任务)
    if not request:
        return 0.1

    # 获取请求的路径
    path = request.url.path

    # 针对不同路由设置采样率
    if path == "/api/payment/process":
        # 核心支付接口,全量采样
        return 1.0
    elif path.startswith("/api/admin/"):
        # 后台管理接口,50%采样率
        return 0.5
    elif path in ["/api/health", "/api/status"]:
        # 健康检查接口,低采样率
        return 0.01
    else:
        # 默认采样率
        return 0.1

sentry_sdk.init(
    dsn="你的Sentry DSN",
    traces_sampler=traces_sampler,
    # 其他配置项
)

如果需要通过路由名称(而非路径)匹配,可以借助request.scope中的路由对象:

def traces_sampler(sampling_context: Dict[str, Any]) -> float:
    request: Request = sampling_context.get("request")
    if not request:
        return 0.1

    # 获取路由对象
    route = request.scope.get("route")
    if route and route.name == "create_order":
        # 匹配到名为create_order的路由,全量采样
        return 1.0

    return 0.1

注:route.name对应FastAPI定义路由时设置的name参数,例如@app.post("/api/orders", name="create_order")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 02:07:11