| | | 1 | | using System.Diagnostics.CodeAnalysis; |
| | | 2 | | using System.Diagnostics.Metrics; |
| | | 3 | | |
| | | 4 | | |
| | | 5 | | namespace Api.Dev; |
| | | 6 | | [ExcludeFromCodeCoverage(Justification = "Development")] |
| | | 7 | | public class NorthiwndMetrics { |
| | | 8 | | public const string MeterName = "Northwind-Api"; |
| | | 9 | | |
| | | 10 | | private readonly Counter<long> _counter; |
| | | 11 | | private readonly Histogram<double> _duration; |
| | | 12 | | |
| | | 13 | | public NorthiwndMetrics(IMeterFactory meterFactory) { |
| | | 14 | | var meter = meterFactory.Create(MeterName); |
| | | 15 | | _counter = meter.CreateCounter<long>("northwind.api.request.count"); |
| | | 16 | | _duration = meter.CreateHistogram<double>("northwind.api.request.duration", "ms"); |
| | | 17 | | } |
| | | 18 | | |
| | | 19 | | public void IncreaseRequestCount() { |
| | | 20 | | _counter.Add(1); |
| | | 21 | | } |
| | | 22 | | |
| | | 23 | | public TrackedRequestDuration MeasureRequestDuration() { |
| | | 24 | | return new TrackedRequestDuration(_duration); |
| | | 25 | | } |
| | | 26 | | } |
| | | 27 | | |
| | | 28 | | #pragma warning disable S3881 // "IDisposable" should be implemented correctly |
| | 0 | 29 | | public class TrackedRequestDuration(Histogram<double> histogram) : IDisposable { |
| | | 30 | | #pragma warning restore S3881 // "IDisposable" should be implemented correctly |
| | 0 | 31 | | private readonly long _startTime = TimeProvider.System.GetTimestamp(); |
| | 0 | 32 | | private readonly Histogram<double> _histogram = histogram; |
| | | 33 | | |
| | 0 | 34 | | public void Dispose() { |
| | 0 | 35 | | var elapsedTime = TimeProvider.System.GetElapsedTime(_startTime); |
| | 0 | 36 | | _histogram.Record(elapsedTime.TotalMilliseconds); |
| | 0 | 37 | | GC.SuppressFinalize(this); |
| | 0 | 38 | | } |
| | | 39 | | } |