Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a Serilog enricher that reads from HttpContext.TraceIdentifier?

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?

like image 940
NathanAldenSr Avatar asked Oct 21 '16 20:10

NathanAldenSr


1 Answers

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().

like image 53
user764754 Avatar answered Dec 17 '22 06:12

user764754