From f1c1bd7118621c0cf4d223a2ebcaf305baad6df2 Mon Sep 17 00:00:00 2001 From: Nicholas Blumhardt Date: Wed, 11 Oct 2023 17:46:29 +1000 Subject: [PATCH 1/2] Collect trace and span ids in request completion events --- .../AspNetCore/RequestLoggingMiddleware.cs | 17 ++++++++++++++--- .../Serilog.AspNetCore.csproj | 4 ++-- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/Serilog.AspNetCore/AspNetCore/RequestLoggingMiddleware.cs b/src/Serilog.AspNetCore/AspNetCore/RequestLoggingMiddleware.cs index 0b0b3eb..a0bd873 100644 --- a/src/Serilog.AspNetCore/AspNetCore/RequestLoggingMiddleware.cs +++ b/src/Serilog.AspNetCore/AspNetCore/RequestLoggingMiddleware.cs @@ -32,7 +32,7 @@ class RequestLoggingMiddleware readonly Func> _getMessageTemplateProperties; readonly ILogger? _logger; readonly bool _includeQueryInRequestPath; - static readonly LogEventProperty[] NoProperties = new LogEventProperty[0]; + static readonly LogEventProperty[] NoProperties = Array.Empty(); public RequestLoggingMiddleware(RequestDelegate next, DiagnosticContext diagnosticContext, RequestLoggingOptions options) { @@ -82,7 +82,6 @@ bool LogCompletion(HttpContext httpContext, DiagnosticContextCollector collector if (!logger.IsEnabled(level)) return false; - // Enrich diagnostic context _enrichDiagnosticContext?.Invoke(_diagnosticContext, httpContext); if (!collector.TryComplete(out var collectedProperties, out var collectedException)) @@ -91,7 +90,19 @@ bool LogCompletion(HttpContext httpContext, DiagnosticContextCollector collector // Last-in (correctly) wins... var properties = collectedProperties.Concat(_getMessageTemplateProperties(httpContext, GetPath(httpContext, _includeQueryInRequestPath), elapsedMs, statusCode)); - var evt = new LogEvent(DateTimeOffset.Now, level, ex ?? collectedException, _messageTemplate, properties); + var (traceId, spanId) = Activity.Current is { } activity ? + (activity.TraceId, activity.SpanId) : + (default(ActivityTraceId), default(ActivitySpanId)); + + var evt = new LogEvent( + DateTimeOffset.Now, + level, + ex ?? collectedException, + _messageTemplate, + properties, + traceId, + spanId); + logger.Write(evt); return false; diff --git a/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj b/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj index 7356343..cb25916 100644 --- a/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj +++ b/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj @@ -3,7 +3,7 @@ Serilog support for ASP.NET Core logging - 7.0.0 + 7.0.1 Microsoft;Serilog Contributors net462;netstandard2.0;netstandard2.1;net6.0;net7.0 true @@ -23,7 +23,7 @@ - + From 75c35baae680934f4d9d89d834ed96622aaed27f Mon Sep 17 00:00:00 2001 From: Nicholas Blumhardt Date: Wed, 11 Oct 2023 18:13:36 +1000 Subject: [PATCH 2/2] Add test and update sample --- samples/Sample/Program.cs | 7 +++++-- samples/Sample/Sample.csproj | 4 ++++ src/Serilog.AspNetCore/Serilog.AspNetCore.csproj | 4 +++- .../SerilogWebHostBuilderExtensionsTests.cs | 13 +++++++++++++ 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/samples/Sample/Program.cs b/samples/Sample/Program.cs index 7b91b07..d03a62d 100644 --- a/samples/Sample/Program.cs +++ b/samples/Sample/Program.cs @@ -1,4 +1,5 @@ using Serilog; +using Serilog.Templates; namespace Sample; @@ -39,6 +40,8 @@ public static IHostBuilder CreateHostBuilder(string[] args) => .ReadFrom.Configuration(context.Configuration) .ReadFrom.Services(services) .Enrich.FromLogContext() - .WriteTo.Console()) + .WriteTo.Console(new ExpressionTemplate( + // Include trace and span ids when present. + "[{@t:HH:mm:ss} {@l:u3}{#if @tr is not null} ({@tr}:{@sp}){#end}] {@m}\n{@x}"))) .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()); -} \ No newline at end of file +} diff --git a/samples/Sample/Sample.csproj b/samples/Sample/Sample.csproj index 698f224..d8af183 100644 --- a/samples/Sample/Sample.csproj +++ b/samples/Sample/Sample.csproj @@ -7,5 +7,9 @@ + + + + diff --git a/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj b/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj index cb25916..4435023 100644 --- a/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj +++ b/src/Serilog.AspNetCore/Serilog.AspNetCore.csproj @@ -27,7 +27,7 @@ - + @@ -36,6 +36,8 @@ + + diff --git a/test/Serilog.AspNetCore.Tests/SerilogWebHostBuilderExtensionsTests.cs b/test/Serilog.AspNetCore.Tests/SerilogWebHostBuilderExtensionsTests.cs index 176cc78..7d4f8a1 100644 --- a/test/Serilog.AspNetCore.Tests/SerilogWebHostBuilderExtensionsTests.cs +++ b/test/Serilog.AspNetCore.Tests/SerilogWebHostBuilderExtensionsTests.cs @@ -164,6 +164,19 @@ WebApplicationFactory Setup( return web; } + + [Fact] + public async Task RequestLoggingMiddlewareShouldAddTraceAndSpanIds() + { + var (sink, web) = Setup(); + + await web.CreateClient().GetAsync("/resource"); + + var completionEvent = sink.Writes.First(logEvent => Matching.FromSource()(logEvent)); + + Assert.NotNull(completionEvent.TraceId); + Assert.NotNull(completionEvent.SpanId); + } (SerilogSink, WebApplicationFactory) Setup( Action? configureOptions = null,