1

I'm creating a custom target but I see no way to access layout renderers value such as aspnet-traceidentifier https://github.com/NLog/NLog/wiki/AspNetTraceIdentifier-Layout-Renderer from Write method.

Here is the code I use :

[Target("CustomTarget")]
public sealed class CustomTarget : AsyncTaskTarget
{
    protected override async Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token)
    {
        var layout = new NLog.Layouts.SimpleLayout("${aspnet-traceidentifier}");
        string logMessage = this.Layout.Render(logEvent);

        string identifier = layout.Render(logEvent);
        // identifier is empty here...
        
        identifier = RenderLogEvent("${aspnet-traceidentifier}", logEvent);
        
        // identifier is empty here...
    }  
}
Dragouf
  • 4,676
  • 4
  • 48
  • 55

1 Answers1

1

Maybe something like this:

    [Target("CustomTarget")] 
    public sealed class CustomTarget : AsyncTaskTarget
    { 
        public CustomTarget()
        {
            this.CorrelationId = "${aspnet-traceidentifier}";
        }
 
        public Layout CorrelationId { get; set; }
 
        protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token)
        { 
            string logMessage = this.RenderLogEvent(this.Layout, logEvent); 
            string correlationId = this.RenderLogEvent(this.CorrelationId, logEvent); 

            // TODO - write message
        } 
    } 

See also the tutorial for writing custom NLog target: https://github.com/NLog/NLog/wiki/How-to-write-a-custom-async-target

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70