FLICKER
FLICKER

Reputation: 6683

NLog seems to be writing incorrect value in database

I'm using NLog for logging into database. It seems to me its misplacing value in columns. For instance, it writes StackTrace in Message column and Exception information in StackTrace column

Configuration:

<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwConfigExceptions="true" throwExceptions="true">
    <targets>
        <target name="database" type="Database" connectionString="Data Source=Server1;initial catalog=MyDb;Integrated Security=True;">
            <commandText>insert into dbo.AppException ([Level], Logger, Message, Exception, StackTrace) values (@Level, @Logger, @Message, @Exception, @StackTrace);</commandText>
            <parameter name="@Level" layout="${level}" />
            <parameter name="@Logger" layout="${logger}" />
            <parameter name="@Message" layout="${message}" />
            <parameter name="@Exception" layout="${exception}" />
            <parameter name="@StackTrace" layout="${stacktrace}" />
            <dbProvider>System.Data.SqlClient</dbProvider>
        </target>
    </targets>
    <rules>
        <logger name="*" minlevel="Error" writeTo="database" />
    </rules>
</nlog>

My test code:

throw new IOException("This is my message");

Logging code:

logger.Error(ex);

Below is a sample row in database

enter image description here

In my opinion, the value in "Exception" field should be written in "Message" column and value of "StackTrace" should be written into "Exception" column and finally value of "Message" should be written in "StackTrace".

Is there anything wrong in my configuration or my expectation is wrong?

Upvotes: 1

Views: 213

Answers (2)

FLICKER
FLICKER

Reputation: 6683

After reading answer posted by @Rolf, I found my nlog.config setting is not correct. The format setting in nlog is important

NLog Document

I changed my nlog to below and it worked as expected

<parameter name="@Message" layout="${exception:format=message}" />
<parameter name="@Exception" layout="${exception:format=type}" />
<parameter name="@StackTrace" layout="${exception:format=stacktrace}" />

enter image description here

Upvotes: 3

Rolf Kristensen
Rolf Kristensen

Reputation: 19867

I'm guessing you are logging the exception like this:

catch (Exception ex)
{
   _logger.Error(ex);  // ${message} will become ex.ToString(), since no message provided.
}

If you changed to this instead:

catch (Exception ex)
{
   _logger.Error(ex, "Exception caught while testing");
}

And updated NLog.config to this:

<parameter name="@Exception" layout="${exception:format=tostring,data}" />

Then you will probably get what you want.

Upvotes: 2

Related Questions