1

我正在创建一个自定义目标,但我看不到从 Write 方法访问布局渲染器值的方法,例如 aspnet-traceidentifier https://github.com/NLog/NLog/wiki/AspNetTraceIdentifier-Layout-Renderer 。

这是我使用的代码:

[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...
    }  
}
4

1 回答 1

1

也许是这样的:

    [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
        } 
    } 

另请参阅编写自定义 NLog 目标的教程:https ://github.com/NLog/NLog/wiki/How-to-write-a-custom-async-target

于 2021-05-06T14:49:04.810 回答