|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Diagnostics; |
| 4 | +using System.Linq; |
| 5 | +using System.Threading; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using Serilog; |
| 8 | +using Serilog.Events; |
| 9 | +using Serilog.Parsing; |
| 10 | + |
| 11 | +namespace Roastery.Metrics; |
| 12 | + |
| 13 | +public class RoasteryMetrics |
| 14 | +{ |
| 15 | + public class Sample |
| 16 | + { |
| 17 | + /* |
| 18 | + Adding new metrics: |
| 19 | +
|
| 20 | + 1. Add a new key type, `TKey` for the metric's attributes using structural equality. |
| 21 | + 2. Add a `Dictionary<TKey, TMetric>` property for the metric where `TMetric` is its collection type. |
| 22 | + 3. Add a method to `RoasterMetrics` to add a sample to the metric for a given key. |
| 23 | + 4. Add support in `ToLogEvents` for the new metric. |
| 24 | + */ |
| 25 | + |
| 26 | + // `HttpRequestDuration`: histogram |
| 27 | + public record struct HttpRequestDurationKey(string Path, int StatusCode); |
| 28 | + public readonly Dictionary<HttpRequestDurationKey, ExponentialHistogram> HttpRequestDuration = new(); |
| 29 | + |
| 30 | + // `OrdersCreated`: counter |
| 31 | + public ulong OrdersCreated; |
| 32 | + |
| 33 | + // `OrdersShipped`: counter |
| 34 | + public ulong OrdersShipped; |
| 35 | + |
| 36 | + static readonly MessageTemplate Template = new MessageTemplateParser().Parse("Metrics sampled"); |
| 37 | + |
| 38 | + public IEnumerable<LogEvent> ToLogEvents(ILogger logger, PropertyNameMapping propertyNameMapping, DateTimeOffset timestamp) |
| 39 | + { |
| 40 | + foreach (var (key, metric) in HttpRequestDuration) |
| 41 | + { |
| 42 | + yield return ToLogEvent( |
| 43 | + logger, |
| 44 | + propertyNameMapping, |
| 45 | + timestamp, |
| 46 | + new Dictionary<string, object> |
| 47 | + { |
| 48 | + { "HttpRequestDuration", new { kind = "Exponential", unit = "ms", description = "The time taken to fully process a request" } } |
| 49 | + }, |
| 50 | + new |
| 51 | + { |
| 52 | + HttpRequestDuration = new { |
| 53 | + buckets = metric.Buckets |
| 54 | + .Select(bucket => new { midpoint = bucket.Key, count = bucket.Value }).ToArray(), |
| 55 | + scale = metric.Scale, |
| 56 | + min = metric.Min, |
| 57 | + max = metric.Max, |
| 58 | + count = metric.Total |
| 59 | + }, |
| 60 | + key.Path, |
| 61 | + key.StatusCode |
| 62 | + } |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | + yield return ToLogEvent( |
| 67 | + logger, |
| 68 | + propertyNameMapping, |
| 69 | + timestamp, |
| 70 | + new Dictionary<string, object> |
| 71 | + { |
| 72 | + { "OrdersCreated", new { kind = "Counter", unit = "orders", description = "The total number of orders created in the system" } }, |
| 73 | + { "OrdersShipped", new { kind = "Counter", unit = "orders", description = "The total number of orders shipped in the system" } } |
| 74 | + }, |
| 75 | + new |
| 76 | + { |
| 77 | + OrdersCreated, |
| 78 | + OrdersShipped |
| 79 | + } |
| 80 | + ); |
| 81 | + } |
| 82 | + |
| 83 | + static LogEvent ToLogEvent(ILogger logger, PropertyNameMapping propertyNameMapping, DateTimeOffset timestamp, Dictionary<string, object> definitions, object samples) |
| 84 | + { |
| 85 | + logger.BindProperty(propertyNameMapping.MetricDefinitions, definitions, true, out var definitionsProperty); |
| 86 | + logger.BindProperty(propertyNameMapping.MetricSamples, samples, true, out var sampleProperty); |
| 87 | + |
| 88 | + return new LogEvent(timestamp, LogEventLevel.Information, null, Template, |
| 89 | + [definitionsProperty!, sampleProperty!]); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + // Access to the current sample is synchronized through a lock |
| 94 | + // This is a simple way to implement deltas for arbitrary types |
| 95 | + readonly Lock _lock = new(); |
| 96 | + Sample _current = new(); |
| 97 | + |
| 98 | + public void RecordHttpRequestDuration(Sample.HttpRequestDurationKey key, double rawValue) |
| 99 | + { |
| 100 | + lock (_lock) |
| 101 | + { |
| 102 | + if (!_current.HttpRequestDuration.TryGetValue(key, out var metric)) |
| 103 | + { |
| 104 | + metric = new ExponentialHistogram(); |
| 105 | + _current.HttpRequestDuration.Add(key, metric); |
| 106 | + } |
| 107 | + |
| 108 | + metric.Record(rawValue); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + public void RecordOrderCreated() |
| 113 | + { |
| 114 | + lock (_lock) |
| 115 | + { |
| 116 | + _current.OrdersCreated += 1; |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + public void RecordOrderShipped() |
| 121 | + { |
| 122 | + lock (_lock) |
| 123 | + { |
| 124 | + _current.OrdersShipped += 1; |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + public (DateTimeOffset, Sample) Take() |
| 129 | + { |
| 130 | + var timestamp = DateTimeOffset.UtcNow; |
| 131 | + |
| 132 | + var current = new Sample(); |
| 133 | + |
| 134 | + lock (_lock) |
| 135 | + { |
| 136 | + (current, _current) = (_current, current); |
| 137 | + } |
| 138 | + |
| 139 | + return (timestamp, current); |
| 140 | + } |
| 141 | + |
| 142 | + public static Task PeriodicSample( |
| 143 | + RoasteryMetrics metrics, |
| 144 | + TimeSpan samplingInterval, |
| 145 | + Func<DateTimeOffset, Sample, CancellationToken, Task> sample, |
| 146 | + CancellationToken cancellationToken) |
| 147 | + { |
| 148 | + return Task.Run(async () => |
| 149 | + { |
| 150 | + var waitFor = samplingInterval; |
| 151 | + while (!cancellationToken.IsCancellationRequested) |
| 152 | + { |
| 153 | + await Task.Delay(waitFor, cancellationToken); |
| 154 | + |
| 155 | + var stopwatch = Stopwatch.StartNew(); |
| 156 | + |
| 157 | + try |
| 158 | + { |
| 159 | + var (timestamp, current) = metrics.Take(); |
| 160 | + await sample(timestamp, current, cancellationToken); |
| 161 | + } |
| 162 | + catch |
| 163 | + { |
| 164 | + // Ignored |
| 165 | + } |
| 166 | + |
| 167 | + // Account for the time taken to produce the sample when computing |
| 168 | + // the next interval to wait for |
| 169 | + var elapsed = stopwatch.Elapsed; |
| 170 | + waitFor = elapsed < samplingInterval ? samplingInterval - stopwatch.Elapsed : samplingInterval; |
| 171 | + } |
| 172 | + }, cancellationToken); |
| 173 | + } |
| 174 | +} |
0 commit comments