Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Collect trace and span ids in request completion events #349

Merged
merged 2 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions samples/Sample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Serilog;
using Serilog.Templates;

namespace Sample;

Expand Down Expand Up @@ -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<Startup>());
}
}
4 changes: 4 additions & 0 deletions samples/Sample/Sample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,9 @@
<ItemGroup>
<ProjectReference Include="..\..\src\Serilog.AspNetCore\Serilog.AspNetCore.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Serilog.Expressions" Version="4.0.0-*" />
</ItemGroup>

</Project>
17 changes: 14 additions & 3 deletions src/Serilog.AspNetCore/AspNetCore/RequestLoggingMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class RequestLoggingMiddleware
readonly Func<HttpContext, string, double, int, IEnumerable<LogEventProperty>> _getMessageTemplateProperties;
readonly ILogger? _logger;
readonly bool _includeQueryInRequestPath;
static readonly LogEventProperty[] NoProperties = new LogEventProperty[0];
static readonly LogEventProperty[] NoProperties = Array.Empty<LogEventProperty>();

public RequestLoggingMiddleware(RequestDelegate next, DiagnosticContext diagnosticContext, RequestLoggingOptions options)
{
Expand Down Expand Up @@ -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))
Expand All @@ -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;
Expand Down
8 changes: 5 additions & 3 deletions src/Serilog.AspNetCore/Serilog.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<Description>Serilog support for ASP.NET Core logging</Description>
<!-- This must match the major and minor components of the referenced *.Extensions.* packages (and highest supported .NET TFM). -->
<VersionPrefix>7.0.0</VersionPrefix>
<VersionPrefix>7.0.1</VersionPrefix>
<Authors>Microsoft;Serilog Contributors</Authors>
<TargetFrameworks>net462;netstandard2.0;netstandard2.1;net6.0;net7.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
Expand All @@ -23,11 +23,11 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog" Version="3.1.0-*" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0-*" />
</ItemGroup>

<ItemGroup>
Expand All @@ -36,6 +36,8 @@
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<!-- Temporary addition to pull in trace/span support -->
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.1-*" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' != 'net462' and '$(TargetFramework)' != 'netstandard2.0' and '$(TargetFramework)' != 'netstandard2.1' ">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,19 @@ WebApplicationFactory<TestStartup> 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<RequestLoggingMiddleware>()(logEvent));

Assert.NotNull(completionEvent.TraceId);
Assert.NotNull(completionEvent.SpanId);
}

(SerilogSink, WebApplicationFactory<TestStartup>) Setup(
Action<RequestLoggingOptions>? configureOptions = null,
Expand Down