|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Diagnostics; |
| 4 | +using System.Linq; |
| 5 | +using System.Text.Json; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using ManagedCode.Communication.CollectionResultT; |
| 8 | +using ManagedCode.Communication.Extensions.Telemetry; |
| 9 | +using ManagedCode.Communication.Telemetry; |
| 10 | +using Microsoft.Extensions.DependencyInjection; |
| 11 | +using Microsoft.Extensions.Hosting; |
| 12 | +using Microsoft.Extensions.Logging; |
| 13 | +using OpenTelemetry; |
| 14 | +using OpenTelemetry.Logs; |
| 15 | +using OpenTelemetry.Metrics; |
| 16 | +using OpenTelemetry.Trace; |
| 17 | +using Shouldly; |
| 18 | + |
| 19 | +namespace ManagedCode.Communication.Tests.Telemetry; |
| 20 | + |
| 21 | +[NotInParallel] |
| 22 | +public sealed class AutomaticFailureTelemetryTests |
| 23 | +{ |
| 24 | + private const string FailureTitle = "automatic-failure-test"; |
| 25 | + private const string FailureDetail = "automatic failure detail"; |
| 26 | + private const string ParentOperation = "automatic-failure-parent"; |
| 27 | + private const string ExceptionEvent = "exception"; |
| 28 | + private const string ExceptionStackTrace = "exception.stacktrace"; |
| 29 | + private const string OriginalExceptionProperty = "OriginalException"; |
| 30 | + private const string ParentActivityTag = "problem.title"; |
| 31 | + private const string ValidationField = "email"; |
| 32 | + |
| 33 | + [Test] |
| 34 | + public async Task HostRegistration_ShouldExportAutomaticLogsTracesAndMetrics() |
| 35 | + { |
| 36 | + var spans = new List<Activity>(); |
| 37 | + var logs = new List<(LogLevel Level, Exception? Exception, ActivityTraceId TraceId, ActivitySpanId SpanId, string? Message)>(); |
| 38 | + long createdFailures = 0; |
| 39 | + var builder = Host.CreateApplicationBuilder(); |
| 40 | + builder.Logging.ClearProviders(); |
| 41 | + builder.Logging.AddOpenTelemetry(options => |
| 42 | + { |
| 43 | + options.IncludeFormattedMessage = true; |
| 44 | + options.AddProcessor( |
| 45 | + new SimpleLogRecordExportProcessor(new CaptureExporter<LogRecord>(record => |
| 46 | + { |
| 47 | + if (record.CategoryName == typeof(Result).FullName) |
| 48 | + { |
| 49 | + logs.Add((record.LogLevel, record.Exception, record.TraceId, record.SpanId, record.FormattedMessage)); |
| 50 | + } |
| 51 | + }))); |
| 52 | + }); |
| 53 | + builder.AddCommunicationTelemetry().ShouldBeSameAs(builder); |
| 54 | + builder.AddCommunicationTelemetry(); // Repeated ServiceDefaults registration is harmless. |
| 55 | + builder.Services.AddOpenTelemetry() |
| 56 | + .WithTracing(tracing => tracing.AddProcessor(new SimpleActivityExportProcessor( |
| 57 | + new CaptureExporter<Activity>(spans.Add)))) |
| 58 | + .WithMetrics(metrics => metrics.AddReader(new PeriodicExportingMetricReader( |
| 59 | + new CaptureExporter<Metric>(metric => |
| 60 | + { |
| 61 | + if (metric.Name == CommunicationTelemetry.CreatedFailureCounterName) |
| 62 | + { |
| 63 | + foreach (ref readonly var point in metric.GetMetricPoints()) |
| 64 | + { |
| 65 | + createdFailures += point.GetSumLong(); |
| 66 | + } |
| 67 | + } |
| 68 | + }), exportIntervalMilliseconds: int.MaxValue))); |
| 69 | + using var host = builder.Build(); |
| 70 | + await host.StartAsync(); |
| 71 | + using var parent = CommunicationTelemetry.StartActivity(ParentOperation); |
| 72 | + parent.ShouldNotBeNull(); |
| 73 | + Exception original; |
| 74 | + try |
| 75 | + { |
| 76 | + throw new InvalidOperationException(FailureDetail); |
| 77 | + } |
| 78 | + catch (InvalidOperationException exception) |
| 79 | + { |
| 80 | + original = exception; |
| 81 | + } |
| 82 | + |
| 83 | + var result = Result<int>.Fail(original); |
| 84 | + Result.Fail(result.Problem!).IsFailed.ShouldBeTrue(); |
| 85 | + CollectionResult<int>.Fail(result.Problem!).IsFailed.ShouldBeTrue(); |
| 86 | + Result.Succeed().IsSuccess.ShouldBeTrue(); |
| 87 | + Result<int>.Succeed(1).IsSuccess.ShouldBeTrue(); |
| 88 | + logs.Count.ShouldBe(1); |
| 89 | + logs[0].Level.ShouldBe(LogLevel.Error); |
| 90 | + logs[0].Exception.ShouldBeSameAs(original); |
| 91 | + logs[0].TraceId.ShouldBe(parent.TraceId); |
| 92 | + parent.Status.ShouldBe(ActivityStatusCode.Unset); |
| 93 | + var failure = spans.Single(span => span.OperationName == CommunicationTelemetry.CreatedFailureActivityName); |
| 94 | + logs[0].SpanId.ShouldBe(failure.SpanId); |
| 95 | + failure.Status.ShouldBe(ActivityStatusCode.Error); |
| 96 | + failure.ParentSpanId.ShouldBe(parent.SpanId); |
| 97 | + failure.Events.Single(e => e.Name == ExceptionEvent).Tags |
| 98 | + .Single(tag => tag.Key == ExceptionStackTrace).Value.ShouldNotBeNull(); |
| 99 | + using var json = JsonDocument.Parse(JsonSerializer.Serialize(result)); |
| 100 | + json.RootElement.GetProperty(CommunicationJsonNames.Problem) |
| 101 | + .TryGetProperty(OriginalExceptionProperty, out _).ShouldBeFalse(); |
| 102 | + JsonSerializer.Serialize(result).ShouldNotContain(original.StackTrace!); |
| 103 | + |
| 104 | + Result.Fail(FailureTitle, FailureDetail).IsFailed.ShouldBeTrue(); |
| 105 | + logs.Count.ShouldBe(2); |
| 106 | + logs[1].Level.ShouldBe(LogLevel.Warning); |
| 107 | + logs[1].Exception.ShouldBeNull(); |
| 108 | + logs[1].Message.ShouldNotBeNull(); |
| 109 | + logs[1].Message!.ShouldContain(FailureTitle); |
| 110 | + logs[1].Message!.ShouldContain(FailureDetail); |
| 111 | + |
| 112 | + host.Services.GetRequiredService<MeterProvider>().ForceFlush().ShouldBeTrue(); |
| 113 | + createdFailures.ShouldBe(2); |
| 114 | + await host.StopAsync(); |
| 115 | + } |
| 116 | + |
| 117 | + [Test] |
| 118 | + public void FailureFactories_ShouldTraceEveryShapeAndLeaveParentSuccessful() |
| 119 | + { |
| 120 | + var spans = new List<Activity>(); |
| 121 | + using var listener = new ActivityListener |
| 122 | + { |
| 123 | + ShouldListenTo = source => source.Name == CommunicationTelemetry.SourceName, |
| 124 | + Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllDataAndRecorded, |
| 125 | + ActivityStopped = spans.Add |
| 126 | + }; |
| 127 | + ActivitySource.AddActivityListener(listener); |
| 128 | + using var parent = CommunicationTelemetry.StartActivity(ParentOperation); |
| 129 | + Result.Fail(FailureTitle, FailureDetail).IsFailed.ShouldBeTrue(); |
| 130 | + Result<int>.Fail(FailureTitle, FailureDetail).IsFailed.ShouldBeTrue(); |
| 131 | + CollectionResult<int>.Fail(FailureTitle, FailureDetail).IsFailed.ShouldBeTrue(); |
| 132 | + Result.FailValidation((ValidationField, FailureDetail)).IsInvalid.ShouldBeTrue(); |
| 133 | + spans.Count.ShouldBe(4); |
| 134 | + spans.ShouldAllBe(span => span.Status == ActivityStatusCode.Error); |
| 135 | + spans.Count(span => Equals(span.GetTagItem(ParentActivityTag), FailureTitle)).ShouldBe(3); |
| 136 | + parent!.Status.ShouldBe(ActivityStatusCode.Unset); |
| 137 | + } |
| 138 | + |
| 139 | + [Test] |
| 140 | + public async Task From_WhenDelegatesThrow_ShouldImmediatelyRecordStackTraces() |
| 141 | + { |
| 142 | + var spans = new List<Activity>(); |
| 143 | + using var listener = new ActivityListener |
| 144 | + { |
| 145 | + ShouldListenTo = source => source.Name == CommunicationTelemetry.SourceName, |
| 146 | + Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllDataAndRecorded, |
| 147 | + ActivityStopped = spans.Add |
| 148 | + }; |
| 149 | + ActivitySource.AddActivityListener(listener); |
| 150 | + |
| 151 | + Result<int>.From((Func<int>)ThrowFailure).IsFailed.ShouldBeTrue(); |
| 152 | + (await Result<int>.From((Func<Task<int>>)ThrowTaskFailure)).IsFailed.ShouldBeTrue(); |
| 153 | + (await Result<int>.From((Func<ValueTask<int>>)ThrowValueTaskFailure)).IsFailed.ShouldBeTrue(); |
| 154 | + |
| 155 | + spans.Count.ShouldBe(3); |
| 156 | + foreach (var span in spans) |
| 157 | + { |
| 158 | + span.Status.ShouldBe(ActivityStatusCode.Error); |
| 159 | + var stack = span.Events.Single(e => e.Name == ExceptionEvent).Tags |
| 160 | + .Single(tag => tag.Key == ExceptionStackTrace).Value?.ToString(); |
| 161 | + stack.ShouldNotBeNullOrWhiteSpace(); |
| 162 | + stack.ShouldContain(nameof(ThrowFailure)); |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + private static int ThrowFailure() => throw new InvalidOperationException(FailureDetail); |
| 167 | + |
| 168 | + private static async Task<int> ThrowTaskFailure() |
| 169 | + { |
| 170 | + await Task.Yield(); |
| 171 | + return ThrowFailure(); |
| 172 | + } |
| 173 | + |
| 174 | + private static async ValueTask<int> ThrowValueTaskFailure() |
| 175 | + { |
| 176 | + await Task.Yield(); |
| 177 | + return ThrowFailure(); |
| 178 | + } |
| 179 | + |
| 180 | + private sealed class CaptureExporter<T>(Action<T> capture) : BaseExporter<T> where T : class |
| 181 | + { |
| 182 | + public override ExportResult Export(in Batch<T> batch) |
| 183 | + { |
| 184 | + foreach (var item in batch) |
| 185 | + { |
| 186 | + capture(item); |
| 187 | + } |
| 188 | + |
| 189 | + return ExportResult.Success; |
| 190 | + } |
| 191 | + } |
| 192 | +} |
0 commit comments