问题描述
我正在创建一个自定义目标,但我发现无法从 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...
}
}
解决方法
也许是这样的:
[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