如何设置 NLog 以在日志中显示 sqlexception 行号?
How to setup NLog to show sqlexception linenumber in log?
我有一个可能会产生错误的存储过程。
但是,NLog 只写这样的文本消息
16:08:37.7139|ERROR|ConsoleApplication35.Program|System.Data.SqlClient.SqlException
(0x80131904): Arithmetic overflow error converting expression to data
type int. at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action`1 wrapCloseInAction)
但是SqlException
也有一个LineNumber
属性
如何强制 NLog 也写入行号?
有没有预定义的布局?
选项 1
您可以使用格式 @
( NLog 4.5+)
${exception:format=@}
见docs
format - Format of the output. Must be a comma-separated list of exception properties: Message, Type, ShortType, ToString, Method, StackTrace, Data & @
. This parameter value is case-insensitive. Default: message
@
means serialize all Exception-properties into Json-format. Introduced in NLog 4.5
注意:有可能在使用“toString”格式时也可用:
${exception:format=ToString}
选项 2
如果您需要对输出进行更多控制,例如只有行号,您可以编写自己的布局渲染器(继承自 ExceptionLayoutRenderer
):
private class MyExceptionLayoutRenderer : ExceptionLayoutRenderer {
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
base.Append(builder, logEvent);
// Also write linenumber (C# 7 syntax) at the end.
if (logEvent.Exception is SqlException sqlException)
{
builder.AppendLine($"LineNumber: " + sqlException.LineNumber);
}
}
}
尽快注册(例如app_start, main()):
LayoutRenderer.Register<MyExceptionLayoutRenderer>("myException"); //usage ${myException}
选项 3
NLog 4.6.8 引入了新的格式选项 Properties
:
${exception:format=Message,Properties}
我有一个可能会产生错误的存储过程。 但是,NLog 只写这样的文本消息
16:08:37.7139|ERROR|ConsoleApplication35.Program|System.Data.SqlClient.SqlException (0x80131904): Arithmetic overflow error converting expression to data type int. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
但是SqlException
也有一个LineNumber
属性
如何强制 NLog 也写入行号? 有没有预定义的布局?
选项 1
您可以使用格式 @
( NLog 4.5+)
${exception:format=@}
见docs
format - Format of the output. Must be a comma-separated list of exception properties: Message, Type, ShortType, ToString, Method, StackTrace, Data &
@
. This parameter value is case-insensitive. Default: message
@
means serialize all Exception-properties into Json-format. Introduced in NLog 4.5
注意:有可能在使用“toString”格式时也可用:
${exception:format=ToString}
选项 2
如果您需要对输出进行更多控制,例如只有行号,您可以编写自己的布局渲染器(继承自 ExceptionLayoutRenderer
):
private class MyExceptionLayoutRenderer : ExceptionLayoutRenderer {
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
base.Append(builder, logEvent);
// Also write linenumber (C# 7 syntax) at the end.
if (logEvent.Exception is SqlException sqlException)
{
builder.AppendLine($"LineNumber: " + sqlException.LineNumber);
}
}
}
尽快注册(例如app_start, main()):
LayoutRenderer.Register<MyExceptionLayoutRenderer>("myException"); //usage ${myException}
选项 3
NLog 4.6.8 引入了新的格式选项 Properties
:
${exception:format=Message,Properties}