-
Notifications
You must be signed in to change notification settings - Fork 1.4k
How to Log Exceptions
Exceptions require special treatment in NLog. You need to call the method on the Logger
class which takes an Exception
as its first argument. The method name matches the log level. For instance, to log an exception using the Error
loglevel, do:
logger.Error(ex, "Oops, an exception occured");
Please note: the methods have been changed in NLog 4.0. Previous versions expected the exception after the message.
You typically log exceptions inside a catch handler. An example of logging an exception with the Error
LogLevel is seen in the following:
try
{
// some code which may throw
}
catch (MyException ex)
{
logger.Error(ex, "Got exception."); // NLog 4.0 and newer
logger.Error("Got exception.", ex); // Before NLog 4.0, and now obsolete
}
To write the details of the exception, use the ${exception} in your layout. Depending on the desired output you may want to specify different value for the format
argument. The following example displays the result of calling ToString()
on the exception object.
<nlog>
<targets>
<target name="f" type="File"
layout="${longdate} ${message} ${exception:format=tostring}"/>
</targets>
<rules>
<logger name="*" writeTo="f"/>
</rules>
</nlog>
For simpler scenarios you may directly use the ${message:withException=true}, which is used in the default Layout in NLog v5.0:
<nlog>
<targets>
<target name="f" type="File"
layout="${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}"/>
</targets>
<rules>
<logger name="*" writeTo="f"/>
</rules>
</nlog>
- Troubleshooting Guide - See available NLog Targets and Layouts: https://nlog-project.org/config
- Getting started
- How to use structured logging
- Troubleshooting
- FAQ
- Articles about NLog
-
All targets, layouts and layout renderers
Popular: - Using NLog with NLog.config
- Using NLog with appsettings.json