| | 1 | | using Syki.Back.Metrics; |
| | 2 | | using System.Collections.Concurrent; |
| | 3 | |
|
| | 4 | | namespace Syki.Back.Middlewares; |
| | 5 | |
|
| 2 | 6 | | public class MetricsMiddleware(RequestDelegate next) |
| | 7 | | { |
| | 8 | | public async Task Invoke(HttpContext context) |
| | 9 | | { |
| 7886 | 10 | | context.Response.OnStarting(() => |
| 7886 | 11 | | { |
| 7886 | 12 | | var method = context.Request.Method; |
| 7886 | 13 | | var endpoint = context.Request.Path.ToString(); |
| 7886 | 14 | | var status = context.Response.StatusCode.ToString(); |
| 7886 | 15 | |
|
| 7886 | 16 | | SykiMetricsStore.Requests.AddOrUpdate( |
| 7886 | 17 | | $"{method} {endpoint}", |
| 7886 | 18 | | _ => |
| 7886 | 19 | | { |
| 586 | 20 | | var dict = new ConcurrentDictionary<string, int>(); |
| 586 | 21 | | dict.TryAdd("Total", 1); |
| 586 | 22 | | dict.TryAdd(method, 1); |
| 586 | 23 | | dict.TryAdd(status, 1); |
| 586 | 24 | | return dict; |
| 7886 | 25 | | }, |
| 7886 | 26 | | (key, currentValue) => |
| 7886 | 27 | | { |
| 14658 | 28 | | currentValue.AddOrUpdate("Total", 1, (_, oldValue) => oldValue + 1); |
| 14652 | 29 | | currentValue.AddOrUpdate(method, 1, (_, oldValue) => oldValue + 1); |
| 14582 | 30 | | currentValue.AddOrUpdate(status, 1, (_, oldValue) => oldValue + 1); |
| 7326 | 31 | | return currentValue; |
| 7886 | 32 | | }); |
| 7886 | 33 | |
|
| 7886 | 34 | | return Task.CompletedTask; |
| 7886 | 35 | | }); |
| | 36 | |
|
| 7886 | 37 | | await next(context); |
| 7886 | 38 | | } |
| | 39 | | } |