Created
August 11, 2015 21:34
-
-
Save madslyng/91321dac3ae815178453 to your computer and use it in GitHub Desktop.
Create Serilog Enricher to add Request header in logs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CorrelationIdEnricher : ILogEventEnricher | |
{ | |
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) | |
{ | |
if (logEvent == null) throw new ArgumentNullException("logEvent"); | |
if (HttpContext.Current == null) | |
return; | |
if (HttpContext.Current.Request == null) | |
return; | |
string correlationId = HttpContext.Current.Request.Headers["CorrelationId"]; | |
if (string.IsNullOrWhiteSpace(correlationId)) | |
return; | |
var correlationIdProperty = new LogEventProperty("CorrelationId", new ScalarValue(correlationId)); | |
logEvent.AddPropertyIfAbsent(correlationIdProperty); | |
} | |
} |
this was also helpful for me, as I had a custom header to look for
Heads up instead of HttpContext.Current
(as that is no longer available in the latest .NET versions) you can now inject an IHttpContextAccessor
as per https://stackoverflow.com/a/31243688/2193458
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this helped :D