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

如何为.NET 8自定义Prometheus默认指标:删减、调整桶边界等

.NET 8 API自定义Prometheus默认指标方案

针对默认指标冗余重叠、桶边界不符合需求、标签过多的问题,无需完全禁用默认指标后重建,可通过以下低成本方式调整:

一、过滤冗余重叠指标

使用Prometheus.AspNetCore的指标过滤器,直接移除重复或非必要的指标(比如去掉与http_request_duration_seconds_bucket重叠的microsoft_aspnetcore_hosting_http_server_request_duration_bucket):

builder.Services.AddMetrics(options =>
{
    options.AddFilter((metricName, labels) => 
    {
        // 过滤指定前缀的冗余指标
        return !metricName.StartsWith("microsoft_aspnetcore_hosting_http_server_request_duration");
    });
});

二、调整请求时长指标的桶边界

直接覆盖ASP.NET Core内置请求时长直方图的桶配置,无需重新创建指标:

builder.Services.AddMetrics()
    .AddAspNetCore(options =>
    {
        // 自定义请求时长桶边界(单位:秒)
        options.RequestDurationHistogram = new HistogramConfiguration
        {
            Buckets = new[] { 0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10 }
        };
    });

三、删除冗余标签

通过标签过滤器保留核心标签,移除非必要的标签(如scheme、host等):

builder.Services.AddMetrics(options =>
{
    options.AddLabelFilter((metricName, labelName, labelValue) =>
    {
        // 仅保留业务核心标签
        var allowedLabels = new[] { "controller", "action", "status_code", "method" };
        return allowedLabels.Contains(labelName);
    });
});

四、验证配置效果

启动服务后访问/metrics端点,确认:

  • 冗余指标已被移除
  • 请求时长桶为自定义边界
  • 指标仅保留允许的标签

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 05:21:03