I recently integrated Serilog into several .NET Standard class libraries, including the class libraries used by MVC 6 projects. What I would like to do is enrich the journal entries HttpContext.TraceIdentifier. I wrote an action filter that sets HttpContext.TraceIdentifierthe value of the request header Correlation-ID, 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 can I make Serilog for the duration of this correlation identifier request? Since this is not like a property HttpContext.Current, I am not sure how to create an enrichment that will work. Is it possible?