Search code examples
nlog

How to force nlog to throw an exception when the logging to database fails?


When I take down the database that backs nlog, nothing gets get logged and it seems NLog swallows the problem. Is there any way to configure it to raise and exception or at least to log in a text file that logging failed?

Here is what my configuration looks like:

<?xml version="1.0" ?>
<nlog autoReload="true" throwExceptions="true" internalLogFile="${basedir}/App_Data/nlog.txt" internalLogLevel="Debug"
 internalLogToConsole="true">

 <targets>
 <!--Useful for debugging-->
 <target name="consolelog" type="ColoredConsole"
 layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />



 <target name="databaselog" type="Database">

 <dbProvider>System.Data.SqlClient</dbProvider>

 <!-- database connection parameters -->
 <!-- alternatively you could provide a single 'connectionstring' parameter -->
 <connectionString>Data Source=.\SQLEXPRESSZ;Initial Catalog=aspnetdb;Integrated Security=SSPI</connectionString>

 <commandText>
 insert into NLog_Error ([time_stamp],[level],[host],[type],[source],[logger],[message],[stacktrace],[allxml]) values(@time_stamp,@level,@host,@type,@source,@logger,@message,@stacktrace,@allxml);
 </commandText>

 <parameter name="@time_stamp" layout="${utc_date}" />
 <parameter name="@level" layout="${level}" />
 <parameter name="@host" layout="${machinename}" />
 <parameter name="@type" layout="${exception:format=type}" />
 <parameter name="@source" layout="${callsite:className=true:fileName=false:includeSourcePath=false:methodName=false}" />
 <parameter name="@logger" layout="${logger}" />
 <parameter name="@message" layout="${message}" />
 <parameter name="@stacktrace" layout="${exception:stacktrace}" />
 <parameter name="@allxml" layout="${web_variables}" />

 </target>

 </targets>

 <rules>

 <logger name="*" minlevel="Info" writeTo="databaselog" />
 </rules>

</nlog>

Solution

  • You can force Nlog to throw exception when sql server is not reached by following

    <nlog throwExceptions="true">
     ... your nlog config
    </nlog>
    

    More info here,

    http://nlog-project.org/2010/09/05/new-exception-handling-rules-in-nlog-2-0.html

    It's a new feature in v2.0 so you need v2.0.

    It will not work in earlier versions.

    Also checkout following configuration info

    https://github.com/NLog/NLog/wiki/Logging-Troubleshooting

    which allows Nlog to log it's own exceptions to a specified file.