Skip to content

Commit

Permalink
feat: propagate current trace and span ids through LogEvent (#409)
Browse files Browse the repository at this point in the history
* Propagate current trace and span ids through LogEvent

These fields are essential for tracing and correlating log messages.
It also included in default Serilog JsonFormatter:
https://github.com/serilog/serilog/blob/dev/src/Serilog/Formatting/Json/JsonFormatter.cs#L74-L84

* feat: implements support for distributed tracing in CompactTextFormatter

* test: refactor NormalTextFormatter tests by relying on that Serilog correctly implements support for distributed tracing

* test: refactor NamespacedTextFormatter tests by relying on that Serilog correctly implements support for distributed tracing

* docs(changelog): update

* tests: rename tests

---------

Co-authored-by: FantasticFiasco <[email protected]>
  • Loading branch information
consulting-dev and FantasticFiasco authored Jan 19, 2025
1 parent 5e80c69 commit 8f1730a
Show file tree
Hide file tree
Showing 7 changed files with 140 additions and 4 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ This project adheres to [Semantic Versioning](http://semver.org/) and is followi

## Unreleased

### :zap: Added

- [#409](https://github.com/FantasticFiasco/serilog-sinks-http/issues/409) Have `CompactTextFormatter`, `CompactRenderedTextFormatter`, `NamespacedTextFormatter`, `NormalTextFormatter` and `NormalRenderedTextFormatter` propagate the current trace and span id by writing the values into the JSON payload (contribution by [@consulting-dev](https://github.com/consulting-dev))

## [9.0.0] - 2024-04-14

### :zap: Added
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,20 @@ private void FormatContent(LogEvent logEvent, TextWriter output)
JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
}

if (logEvent.TraceId != null)
{
output.Write(",\"@tr\":\"");
output.Write(logEvent.TraceId.Value.ToHexString());
output.Write('\"');
}

if (logEvent.SpanId != null)
{
output.Write(",\"@sp\":\"");
output.Write(logEvent.SpanId.Value.ToHexString());
output.Write('\"');
}

foreach (var property in logEvent.Properties)
{
var name = property.Key;
Expand All @@ -141,4 +155,4 @@ private static void LogNonFormattableEvent(LogEvent logEvent, Exception e)
logEvent.MessageTemplate.Text,
e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,18 @@ private void FormatContent(LogEvent logEvent, TextWriter output)
JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
}

if (logEvent.TraceId != null)
{
output.Write(",\"TraceId\":");
JsonValueFormatter.WriteQuotedJsonString(logEvent.TraceId.ToString()!, output);
}

if (logEvent.SpanId != null)
{
output.Write(",\"SpanId\":");
JsonValueFormatter.WriteQuotedJsonString(logEvent.SpanId.ToString()!, output);
}

if (logEvent.Properties.Count != 0)
{
WriteProperties(logEvent, output);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,18 @@ private void FormatContent(LogEvent logEvent, TextWriter output)
JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
}

if (logEvent.TraceId != null)
{
output.Write(",\"TraceId\":");
JsonValueFormatter.WriteQuotedJsonString(logEvent.TraceId.ToString(), output);
}

if (logEvent.SpanId != null)
{
output.Write(",\"SpanId\":");
JsonValueFormatter.WriteQuotedJsonString(logEvent.SpanId.ToString(), output);
}

if (logEvent.Properties.Count != 0)
{
WriteProperties(logEvent.Properties, output);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
Expand Down Expand Up @@ -264,6 +265,37 @@ public void SkipNastyException(bool isRenderingMessage)
output.ToString().ShouldBeEmpty();
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public void WriteTraceAndSpanId(bool isRenderingMessage)
{
// Arrange
logger = CreateLogger(isRenderingMessage ?
new CompactRenderedTextFormatter() :
new CompactTextFormatter());

var traceId = ActivityTraceId.CreateRandom();
var spanId = ActivitySpanId.CreateRandom();

// Act
logger.Write(
new LogEvent(
DateTimeOffset.Now,
LogEventLevel.Information,
null,
MessageTemplate.Empty,
[],
traceId,
spanId));

// Assert
var logEvent = GetEvent();

logEvent["@tr"].ShouldBe(traceId.ToHexString());
logEvent["@sp"].ShouldBe(spanId.ToHexString());
}

private ILogger CreateLogger(ITextFormatter formatter)
{
return new LoggerConfiguration()
Expand All @@ -276,4 +308,4 @@ private JObject GetEvent()
{
return JObject.Parse(output.ToString());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
Expand Down Expand Up @@ -434,6 +435,35 @@ public void WriteExceptionAndPropertyUsingSubComponentNamespace(bool isRendering
logEvent["Properties"]["Foo"]["Bar"]["Property"].ShouldBe(42);
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public void WriteTraceAndSpanId(bool isRenderingMessage)
{
// Arrange
logger = CreateLogger(new Formatter("Foo", "Bar", isRenderingMessage));

var traceId = ActivityTraceId.CreateRandom();
var spanId = ActivitySpanId.CreateRandom();

// Act
logger.Write(
new LogEvent(
DateTimeOffset.Now,
LogEventLevel.Information,
null,
MessageTemplate.Empty,
[],
traceId,
spanId));

// Assert
var logEvent = GetEvent();

logEvent["TraceId"].ShouldBe(traceId.ToString());
logEvent["SpanId"].ShouldBe(spanId.ToString());
}

[Theory]
[InlineData(true)]
[InlineData(false)]
Expand Down Expand Up @@ -470,4 +500,4 @@ public Formatter(string component, string subComponent, bool isRenderingMessage)
IsRenderingMessage = isRenderingMessage;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
Expand Down Expand Up @@ -278,6 +279,37 @@ public void SkipNastyException(bool isRenderingMessage)
output.ToString().ShouldBeEmpty();
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public void WriteTraceAndSpanId(bool isRenderingMessage)
{
// Arrange
logger = CreateLogger(isRenderingMessage ?
new NormalRenderedTextFormatter() :
new NormalTextFormatter());

var traceId = ActivityTraceId.CreateRandom();
var spanId = ActivitySpanId.CreateRandom();

// Act
logger.Write(
new LogEvent(
DateTimeOffset.Now,
LogEventLevel.Information,
null,
MessageTemplate.Empty,
[],
traceId,
spanId));

// Assert
var logEvent = GetEvent();

logEvent["TraceId"].ShouldBe(traceId.ToString());
logEvent["SpanId"].ShouldBe(spanId.ToString());
}

private ILogger CreateLogger(ITextFormatter formatter)
{
return new LoggerConfiguration()
Expand All @@ -290,4 +322,4 @@ private JObject GetEvent()
{
return JObject.Parse(output.ToString());
}
}
}

0 comments on commit 8f1730a

Please sign in to comment.