I've recently integrated Serilog into several .NET Standard class libraries, including some class libraries that are used by MVC 6 projects. What I'd like to do is enrich log entries with HttpContext.TraceIdentifier
. I wrote an action filter that sets HttpContext.TraceIdentifier
to a Correlation-ID
request header value, if present:
public override void OnActionExecuting(ActionExecutingContext context)
{
StringValues correlationIds;
Guid correlationId;
if (!context.HttpContext.Request.Headers.TryGetValue(Constants.CorrelationIdHeaderName, out correlationIds) || correlationIds.Count != 1 || !Guid.TryParse(correlationIds[0], out correlationId))
{
correlationId = _guidFactory.Random();
context.HttpContext.Response.Headers.Add(Constants.CorrelationIdHeaderName, correlationId.ToString("D"));
}
context.HttpContext.TraceIdentifier = correlationId.ToString("D");
base.OnActionExecuting(context);
}
The problem is, how do I make Serilog aware, for the life of this request, of the correlation ID? Since it doesn't appear as though there is an HttpContext.Current
property, I'm not sure how to create an enricher that will work. Is this even possible?