Getting HttpContext in NLog Custom Target

Maybe I am missing something basic here - but is it possible to get HttpContext.Current in a custom NLog event?

I am trying to give each request a unique Guid so that I can correlate log messages with one event (i.e. bind each log event for one request). So, I want to save this guide in HttpContext.Current.Items, and then get it in the target NLog and include it in the log message.

Here is my example where I want to access HttpContext.Current:

[Target("AzureTableTarget")]
public class AzureTableTarget : TargetWithLayout
{

    public AzureTableTarget()
    {
        _appSettings = IoCResolver.Get<IAppSettings>();
    }

    protected override void Write(LogEventInfo logEvent)
    {
        var correlationId = HttpContext.Current; //This is always null

        var batchOperation = new TableBatchOperation();
        CxLogEventBuilder.Build(_appSettings, logEvent).ForEach(batchOperation.Insert);
        _loggingTable.ExecuteBatchAsync(batchOperation);
    }
}
+3
source share
1 answer

HttpContext.Current . , , HttpContext.Current .

/ SO, HttpContext.Current, -. ASP.Net web.config.

, , . googling "HttpContext.Current is null", . ASP.NET-, HttpContext.Current .

, System.Diagnostics.CorrelationManager.ActivityId.

ActivityId , "" ( ). , . , ActivityId, , .

ActivityId LayoutRenderer, . . ( NLog 1.0) :

NLog

, "EstimatedBufferSize" , - :

[LayoutRenderer("ActivityId")]
class ActivityIdLayoutRenderer : LayoutRenderer
{
  protected override void Append(StringBuilder builder, LogEventInfo logEvent)
  {
    builder.Append(Trace.CorrelationManager.ActivityId);
  }
}

, Format ActivityIdLayoutRenderer, guid. . ( ). .

NewGuid vs System.Guid.NewGuid(). ToString ( "D" );

. ( NLog git) , Format:

https://github.com/NLog/NLog/blob/master/src/NLog/LayoutRenderers/GuidLayoutRenderer.cs

0

All Articles