Skip to content

Commit e24e4ba

Browse files
authored
Merge pull request #349 from serilog/trace-span-dis
Collect trace and span ids in request completion events
2 parents 5ca0d90 + 75c35ba commit e24e4ba

File tree

5 files changed

+41
-8
lines changed

5 files changed

+41
-8
lines changed

samples/Sample/Program.cs

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using Serilog;
2+
using Serilog.Templates;
23

34
namespace Sample;
45

@@ -39,6 +40,8 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
3940
.ReadFrom.Configuration(context.Configuration)
4041
.ReadFrom.Services(services)
4142
.Enrich.FromLogContext()
42-
.WriteTo.Console())
43+
.WriteTo.Console(new ExpressionTemplate(
44+
// Include trace and span ids when present.
45+
"[{@t:HH:mm:ss} {@l:u3}{#if @tr is not null} ({@tr}:{@sp}){#end}] {@m}\n{@x}")))
4346
.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
44-
}
47+
}

samples/Sample/Sample.csproj

+4
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,9 @@
77
<ItemGroup>
88
<ProjectReference Include="..\..\src\Serilog.AspNetCore\Serilog.AspNetCore.csproj" />
99
</ItemGroup>
10+
11+
<ItemGroup>
12+
<PackageReference Include="Serilog.Expressions" Version="4.0.0-*" />
13+
</ItemGroup>
1014

1115
</Project>

src/Serilog.AspNetCore/AspNetCore/RequestLoggingMiddleware.cs

+14-3
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ class RequestLoggingMiddleware
3232
readonly Func<HttpContext, string, double, int, IEnumerable<LogEventProperty>> _getMessageTemplateProperties;
3333
readonly ILogger? _logger;
3434
readonly bool _includeQueryInRequestPath;
35-
static readonly LogEventProperty[] NoProperties = new LogEventProperty[0];
35+
static readonly LogEventProperty[] NoProperties = Array.Empty<LogEventProperty>();
3636

3737
public RequestLoggingMiddleware(RequestDelegate next, DiagnosticContext diagnosticContext, RequestLoggingOptions options)
3838
{
@@ -82,7 +82,6 @@ bool LogCompletion(HttpContext httpContext, DiagnosticContextCollector collector
8282

8383
if (!logger.IsEnabled(level)) return false;
8484

85-
// Enrich diagnostic context
8685
_enrichDiagnosticContext?.Invoke(_diagnosticContext, httpContext);
8786

8887
if (!collector.TryComplete(out var collectedProperties, out var collectedException))
@@ -91,7 +90,19 @@ bool LogCompletion(HttpContext httpContext, DiagnosticContextCollector collector
9190
// Last-in (correctly) wins...
9291
var properties = collectedProperties.Concat(_getMessageTemplateProperties(httpContext, GetPath(httpContext, _includeQueryInRequestPath), elapsedMs, statusCode));
9392

94-
var evt = new LogEvent(DateTimeOffset.Now, level, ex ?? collectedException, _messageTemplate, properties);
93+
var (traceId, spanId) = Activity.Current is { } activity ?
94+
(activity.TraceId, activity.SpanId) :
95+
(default(ActivityTraceId), default(ActivitySpanId));
96+
97+
var evt = new LogEvent(
98+
DateTimeOffset.Now,
99+
level,
100+
ex ?? collectedException,
101+
_messageTemplate,
102+
properties,
103+
traceId,
104+
spanId);
105+
95106
logger.Write(evt);
96107

97108
return false;

src/Serilog.AspNetCore/Serilog.AspNetCore.csproj

+5-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
<PropertyGroup>
44
<Description>Serilog support for ASP.NET Core logging</Description>
55
<!-- This must match the major and minor components of the referenced *.Extensions.* packages (and highest supported .NET TFM). -->
6-
<VersionPrefix>7.0.0</VersionPrefix>
6+
<VersionPrefix>7.0.1</VersionPrefix>
77
<Authors>Microsoft;Serilog Contributors</Authors>
88
<TargetFrameworks>net462;netstandard2.0;netstandard2.1;net6.0;net7.0</TargetFrameworks>
99
<GenerateDocumentationFile>true</GenerateDocumentationFile>
@@ -23,11 +23,11 @@
2323
</ItemGroup>
2424

2525
<ItemGroup>
26-
<PackageReference Include="Serilog" Version="2.12.0" />
26+
<PackageReference Include="Serilog" Version="3.1.0-*" />
2727
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
2828
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
2929
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
30-
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
30+
<PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0-*" />
3131
</ItemGroup>
3232

3333
<ItemGroup>
@@ -36,6 +36,8 @@
3636
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
3737
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
3838
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
39+
<!-- Temporary addition to pull in trace/span support -->
40+
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.1-*" />
3941
</ItemGroup>
4042

4143
<ItemGroup Condition=" '$(TargetFramework)' != 'net462' and '$(TargetFramework)' != 'netstandard2.0' and '$(TargetFramework)' != 'netstandard2.1' ">

test/Serilog.AspNetCore.Tests/SerilogWebHostBuilderExtensionsTests.cs

+13
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,19 @@ WebApplicationFactory<TestStartup> Setup(
164164

165165
return web;
166166
}
167+
168+
[Fact]
169+
public async Task RequestLoggingMiddlewareShouldAddTraceAndSpanIds()
170+
{
171+
var (sink, web) = Setup();
172+
173+
await web.CreateClient().GetAsync("/resource");
174+
175+
var completionEvent = sink.Writes.First(logEvent => Matching.FromSource<RequestLoggingMiddleware>()(logEvent));
176+
177+
Assert.NotNull(completionEvent.TraceId);
178+
Assert.NotNull(completionEvent.SpanId);
179+
}
167180

168181
(SerilogSink, WebApplicationFactory<TestStartup>) Setup(
169182
Action<RequestLoggingOptions>? configureOptions = null,

0 commit comments

Comments
 (0)