Skip to content
This repository was archived by the owner on May 15, 2023. It is now read-only.

Fixing null in log entry when CorrelationIdHeaderEnricher #33

Merged
merged 4 commits into from
Nov 13, 2019
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
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,28 @@ public void When_CurrentHttpContextIsNotNull_ShouldNot_CreateCorrelationIdProper
Assert.NotNull(evt);
Assert.IsFalse(evt.Properties.ContainsKey("CorrelationId"));
}

[Test]
public void When_MultipleLoggingCallsMade_Should_KeepUsingCreatedCorrelationIdProperty()
{
var httpContext = new DefaultHttpContext();

A.CallTo(() => _httpContextAccessor.HttpContext)
.Returns(httpContext);

LogEvent evt = null;
var log = new LoggerConfiguration()
.Enrich.With(_enricher)
.WriteTo.Sink(new DelegateSink.DelegatingSink(e => evt = e))
.CreateLogger();

log.Information(@"Has a CorrelationId property");

var correlationId = evt.Properties["CorrelationId"].LiteralValue();

log.Information(@"Here is another event");

Assert.AreEqual(correlationId, evt.Properties["CorrelationId"].LiteralValue());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,28 @@ public void When_CurrentHttpContextIsNull_ShouldNot_CreateCorrelationIdProperty(
Assert.NotNull(evt);
Assert.IsFalse(evt.Properties.ContainsKey("CorrelationId"));
}

[Test]
public void When_MultipleLoggingCallsMade_Should_KeepUsingCreatedCorrelationIdProperty()
{
var httpContext = new DefaultHttpContext();

A.CallTo(() => _httpContextAccessor.HttpContext)
.Returns(httpContext);

LogEvent evt = null;
var log = new LoggerConfiguration()
.Enrich.With(_enricher)
.WriteTo.Sink(new DelegateSink.DelegatingSink(e => evt = e))
.CreateLogger();

log.Information(@"Has a CorrelationId property");

var correlationId = evt.Properties["CorrelationId"].LiteralValue();

log.Information(@"Here is another event");

Assert.AreEqual(correlationId, evt.Properties["CorrelationId"].LiteralValue());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)

var correlationIdProperty = new LogEventProperty(CorrelationIdPropertyName, new ScalarValue(correlationId));

logEvent.AddPropertyIfAbsent(correlationIdProperty);
logEvent.AddOrUpdateProperty(correlationIdProperty);
}

private string GetCorrelationId()
Expand All @@ -48,6 +48,10 @@ private string GetCorrelationId()
{
header = values.FirstOrDefault();
}
else if (_contextAccessor.HttpContext.Response.Headers.TryGetValue(_headerKey, out values))
{
header = values.FirstOrDefault();
}

var correlationId = string.IsNullOrEmpty(header)
? Guid.NewGuid().ToString()
Expand Down