Search code examples
c#loggingnlogerror-logging

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?


Solution

  • 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