Skip to content

Instantly share code, notes, and snippets.

@madslyng
Created August 11, 2015 21:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save madslyng/91321dac3ae815178453 to your computer and use it in GitHub Desktop.
Save madslyng/91321dac3ae815178453 to your computer and use it in GitHub Desktop.
Create Serilog Enricher to add Request header in logs
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);
}
}
@vetras
Copy link

vetras commented Aug 9, 2017

this helped :D

@elena-posea
Copy link

this was also helpful for me, as I had a custom header to look for

@cm-nbs
Copy link

cm-nbs commented Jun 20, 2023

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