使用 NLog 记录异常时如何获取目标布局中的异常源?
How to get the exception source in target layout when logging exceptions with NLog?
假设当我们记录 StackTrace 时我们写
<column name="EXCEPTION STACKTRACE" layout="${exception:format=StackTrace}" />
同理,如何在目标布局中写入Exception.source
值?
目前(NLog 4.6.6)您需要扩展当前的ExceptionLayoutRenderer,例如
[LayoutRenderer("exception-custom")]
[ThreadAgnostic]
public class CustomExceptionLayoutRenderer : ExceptionLayoutRenderer
{
public bool RenderSource { get; set; } = true;
protected override void AppendMessage(System.Text.StringBuilder sb, Exception ex)
{
base.AppendMessage(sb, ex);
if (RenderSource && ex.Source != null)
{
sb.Append("Source:");
sb.Append(ex.Source);
}
}
}
用法:
// register
NLog.LayoutRenderers.LayoutRenderer.Register<CustomExceptionLayoutRenderer>("exception-custom");
NLog.LogManager.Configuration = NLog.LogManager.Configuration.Reload(); // reload
在你的 nlog.config:${exception-custom}
, ${exception-custom:RenderSource=false}
等等
在 NLog 4.6.7 中,我们将添加 ${exception:format=Source}
(感谢 Rolf!)
假设当我们记录 StackTrace 时我们写
<column name="EXCEPTION STACKTRACE" layout="${exception:format=StackTrace}" />
同理,如何在目标布局中写入Exception.source
值?
目前(NLog 4.6.6)您需要扩展当前的ExceptionLayoutRenderer,例如
[LayoutRenderer("exception-custom")]
[ThreadAgnostic]
public class CustomExceptionLayoutRenderer : ExceptionLayoutRenderer
{
public bool RenderSource { get; set; } = true;
protected override void AppendMessage(System.Text.StringBuilder sb, Exception ex)
{
base.AppendMessage(sb, ex);
if (RenderSource && ex.Source != null)
{
sb.Append("Source:");
sb.Append(ex.Source);
}
}
}
用法:
// register
NLog.LayoutRenderers.LayoutRenderer.Register<CustomExceptionLayoutRenderer>("exception-custom");
NLog.LogManager.Configuration = NLog.LogManager.Configuration.Reload(); // reload
在你的 nlog.config:${exception-custom}
, ${exception-custom:RenderSource=false}
等等
在 NLog 4.6.7 中,我们将添加 ${exception:format=Source}
(感谢 Rolf!)