Skip to content

Instantly share code, notes, and snippets.

@SlyNet
Created March 24, 2020 09:18
Show Gist options
  • Save SlyNet/66689895a5fd0ca7d512c579c5d63146 to your computer and use it in GitHub Desktop.
Save SlyNet/66689895a5fd0ca7d512c579c5d63146 to your computer and use it in GitHub Desktop.
metrics collecting middleware
public class HttpMetricsMiddleware
{
private readonly RequestDelegate next;
private static readonly Gauge httpInProgress = Prometheus.Metrics.CreateGauge("http_requests_in_progress", "Number or requests in progress", "system");
private static readonly Histogram httpRequestsDuration = Prometheus.Metrics.CreateHistogram("http_requests_duration_seconds", "Duration of http requests per tracking system", "system");
public HttpMetricsMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
string[] subsystem = new string[1];
var path = context.Request.Path;
// will not track request to diagnostics endpoints
if (path.StartsWithSegments("/metrics"))
{
await next(context);
return;
}
using var inprogress = httpInProgress.TrackInProgress();
using var timer = httpRequestsDuration.NewTimer();
try
{
await next(context);
}
catch (Exception)
{
CommonMetrics.ExceptionsOccur.Inc();
throw;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment