标题:使用Prometheus收集C#中API调用的度量
我有一个REST API服务,我想收集所有API调用的信息.我try 使用中间件来收集指标,并将httpContext.Request.Path
作为api_name
标签传递.这种方法在大多数情况下都能正常工作,但是当API在路径中有参数时,例如api/{version}/{id}/doStuff
,它就变得具有挑战性.在这种情况下,API路径中的参数组合将对应大量的标签.
为了解决这个问题,我想在我的终端上使用名为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添加到httpContex
.然而,ActionFilterAttribute
只在_next(httpContext)
开始执行时才起作用,如Microsoft documentation中所述.
Prometheus不允许在创建度量实例后更改标签.所以我不能准确地设置标签.
我可能会使用秒表和Histogram
提供的观察方法.但这不是我想要的.
以下是中间件代码块:
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);
}
}
}