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

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?

+4
1

, .

{RequestId} outputTemplate "0HL0GJPLR7AOD". HttpContext.TraceIdentifier -, {RequestId} , {RequestId}.

, {RequestId} - Microsoft.Extensions.Logging, serilog ( , Serilog.Extensions.Logging).

. Enrich.FromLogContext().

+2

Source: https://habr.com/ru/post/1658494/


All Articles