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

使用Prometheus采集C# API调用指标的路径标签问题咨询

REST API指标采集的标签优化问题

我开发了一个REST API服务,需要采集所有API调用的相关指标。最初尝试通过中间件采集,把httpContext.Request.Path作为api_name标签,多数场景下可行,但遇到带参数的API路径(比如api/{version}/{id}/doStuff)时,会因参数组合过多生成大量冗余标签。

为解决该问题,我计划在端点上使用自定义的TelemetryAttribute(继承自ActionFilterAttribute)指定统一标识,代码实现如下:

public class TelemetryAttribute : ActionFilterAttribute
{
    public TelemetryAttribute(string requestId)
    {
        RequestId = requestId;
    }

    public string RequestId { get; set; }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        context.HttpContext.Items["CustomItem"] = RequestId;
        base.OnActionExecuting(context);
    }
}

原本预期通过该属性把指定的请求ID存入HttpContext,但根据微软官方文档,ActionFilterAttribute要等_next(httpContext)执行后才会生效。

由于Prometheus不允许在指标实例创建后修改标签,导致无法准确设置api_name标签。我虽可借助秒表配合Histogram的observe方法实现,但这并非理想方案。我的中间件代码如下:

public class ApiCallsMetricMiddleware
{
    private readonly ITelemetryCollector _telemetryCollector;
    private readonly RequestDelegate _next;

    public ApiCallsMetricMiddleware(ITelemetryCollector telemetryCollector, RequestDelegate next)
    {
        _telemetryCollector = telemetryCollector;
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        var apiName = httpContext.Items["RequestId"] as string ?? httpContext.Request.Path;

        using (_telemetryCollector.NewHistogramTimer(MetricsDefinitionDeclarations.ApiCallsHistogram, apiName))
        {
            await _next(httpContext);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 16:51:20