How to setup NLog to show sqlexception linenumber in log?


I have a stored procedure which can generate an error. However, NLog writes only text message like that

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)

But SqlException also has a LineNumber property

How to force NLog to write also line number? Is there any predefined layout?

asked on Stack Overflow Aug 7, 2018 by VoimiX • edited Aug 7, 2018 by Julian

1 Answer


Option 1

You could use the format @ ( NLog 4.5+)


See 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

note: it would be possible it is also available when using "toString" format:


Option 2

If you need more control of the output, e.g. only the linenumber, you could write your own layout renderer (inherit from 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);


and register it as soon as possible (e.g. app_start, main()):

LayoutRenderer.Register<MyExceptionLayoutRenderer>("myException"); //usage ${myException}

Option 3

NLog 4.6.8 introduces the new Format-option Properties:

answered on Stack Overflow Aug 7, 2018 by Julian • edited Nov 2, 2019 by Rolf Kristensen

User contributions licensed under CC BY-SA 3.0