Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
When an event id is specified, and a property named EventId exists in…
… the template, the intrinsic event id wins; fixes #273
  • Loading branch information
nblumhardt committed Jun 1, 2025
commit 922a470e1a5204f996baee8cb98f4c92fa161505
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public SerilogLogger(
_provider = provider ?? throw new ArgumentNullException(nameof(provider));

// If a logger was passed, the provider has already added itself as an enricher
_logger = logger ?? Serilog.Log.Logger.ForContext(new[] { provider });
_logger = logger ?? Serilog.Log.Logger.ForContext([provider]);

if (name != null)
{
Expand Down Expand Up @@ -91,7 +91,7 @@ LogEvent PrepareWrite<TState>(LogEventLevel level, EventId eventId, TState state

var properties = new Dictionary<string, LogEventPropertyValue>();

if (state is IEnumerable<KeyValuePair<string, object>> structure)
if (state is IEnumerable<KeyValuePair<string, object?>> structure)
{
foreach (var property in structure)
{
Expand Down Expand Up @@ -155,7 +155,7 @@ LogEvent PrepareWrite<TState>(LogEventLevel level, EventId eventId, TState state

// The overridden `!=` operator on this type ignores `Name`.
if (eventId.Id != 0 || eventId.Name != null)
properties.Add("EventId", _eventIdPropertyCache.GetOrCreatePropertyValue(in eventId));
properties["EventId"] = _eventIdPropertyCache.GetOrCreatePropertyValue(in eventId);

var (traceId, spanId) = Activity.Current is { } activity ?
(activity.TraceId, activity.SpanId) :
Expand Down
16 changes: 16 additions & 0 deletions test/Serilog.Extensions.Logging.Tests/SerilogLoggerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -618,4 +618,20 @@ static void AssertHasScalarProperty(LogEvent logEvent, string name, object? expe
var scalar = Assert.IsType<ScalarValue>(result);
Assert.Equal(expectedValue, scalar.Value);
}

[Fact]
public void ConflictingEventIdTemplatePropertyIsIgnored()
{
var (logger, sink) = SetUp(LogLevel.Trace);

var loggedEventId = 17;
logger.LogInformation(loggedEventId, "{EventId}", 42);

var write = Assert.Single(sink.Writes);
var recordedEventIdProperty = Assert.IsType<StructureValue>(write.Properties["EventId"]);
var recordedEventIdStructure = Assert.Single(recordedEventIdProperty.Properties, p => p.Name == "Id");
var recordedEventIdPropertyValue = Assert.IsType<ScalarValue>(recordedEventIdStructure.Value);
var recordedEventId = Assert.IsType<int>(recordedEventIdPropertyValue.Value);
Assert.Equal(loggedEventId, recordedEventId);
}
}