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?
I don't think you need an enricher for this.
Putting {RequestId}
into the sink's outputTemplate
gives me an ID like "0HL0GJPLR7AOD". If I set HttpContext.TraceIdentifier
right before logging something then {RequestId}
gives me exactly that ID so custom IDs also work with {RequestId}
.
I think {RequestId}
is a Microsoft.Extensions.Logging feature but it works out of the box with serilog (at least when you are using Serilog.Extensions.Logging).
Update: Don't forget to configure Enrich.FromLogContext()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With