【问题标题】:NLog, access layout renderers within custom targetNLog,在自定义目标中访问布局渲染器
【发布时间】:2021-05-06 08:39:08
【问题描述】:

我正在创建一个自定义目标,但我看不到从 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...
    }  
}

【问题讨论】:

    标签: c# asp.net-core nlog add-custom-target


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多