1+ using Microsoft . Extensions . Options ;
2+ using MiniMediaMetadataAPI . Options ;
3+ using Prometheus ;
4+
5+ namespace MiniMediaMetadataAPI . Middlewares ;
6+
7+ public class RequestMiddleware
8+ {
9+ private readonly RequestDelegate _next ;
10+ private readonly ILogger _logger ;
11+ private readonly PrometheusOptions _prometheusOptions ;
12+
13+ public RequestMiddleware (
14+ RequestDelegate next
15+ , ILoggerFactory loggerFactory
16+ , IOptions < PrometheusOptions > prometheusOptions
17+ )
18+ {
19+ _next = next ;
20+ _logger = loggerFactory . CreateLogger < RequestMiddleware > ( ) ;
21+ _prometheusOptions = prometheusOptions . Value ;
22+ }
23+
24+ public async Task Invoke ( HttpContext httpContext )
25+ {
26+ var path = httpContext . Request . Path . Value ;
27+ var method = httpContext . Request . Method ;
28+
29+ var counter = Metrics . CreateCounter ( "MiniMediaMetadataAPI_request_total" , "HTTP Requests Total" , new CounterConfiguration
30+ {
31+ LabelNames = new [ ] { "path" , "method" , "status" }
32+ } ) ;
33+
34+ var statusCode = 200 ;
35+
36+ try
37+ {
38+ await _next . Invoke ( httpContext ) ;
39+ }
40+ catch ( Exception )
41+ {
42+ statusCode = 500 ;
43+ counter . Labels ( path , method , statusCode . ToString ( ) ) . Inc ( ) ;
44+
45+ throw ;
46+ }
47+
48+ if ( path != _prometheusOptions . MetricsUrl )
49+ {
50+ statusCode = httpContext . Response . StatusCode ;
51+ counter . Labels ( path , method , statusCode . ToString ( ) ) . Inc ( ) ;
52+ }
53+ }
54+ }
55+
56+ public static class RequestMiddlewareExtensions
57+ {
58+ public static IApplicationBuilder UseRequestMiddleware ( this IApplicationBuilder builder )
59+ {
60+ return builder . UseMiddleware < RequestMiddleware > ( ) ;
61+ }
62+ }
0 commit comments