How to get NLog to write to database

Ciaran O'Neill picture Ciaran O'Neill · Jun 17, 2009 · Viewed 23.4k times · Source

I'm trying to get NLog to log to my database log table but to no avail. I'm sure my connection string is correct because it's the same used elsewhere in my web.config. Writing out to a file works fine, so I know it's not just NLog, but must be something I'm doing wrong. Below is my NLog configuration:

<!-- NLOG CONFIGURATION -->
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target name="file" xsi:type="File" fileName="${basedir}/logs/Log ${shortdate}.txt" layout="${longdate} ${callsite} ${level}: ${message} ${exception:format=Message,StackTrace} ${stacktrace}" />
      <target type="Database" name="database" connectionstring="MyConnectionString">
        <commandText>
          insert into MyLog ([CreateDate], [Origin], [LogLevel], [Message], [Exception], [StackTrace]) values (@createDate, @origin, @logLevel, @message, @exception, @stackTrace);
        </commandText>
        <parameter name="@createDate" layout="${longdate}"/>
        <parameter name="@origin" layout="${callsite}"/>
        <parameter name="@logLevel" layout="${level}"/>
        <parameter name="@message" layout="${message}"/>
        <parameter name="@exception" layout="${exception:format=Message,StackTrace}"/>
        <parameter name="@stackTrace" layout="${stacktrace}"/>
      </target>
    </targets>
    <rules>
      <logger name="*" writeTo="file"/>
      <logger name="*" appendTo="database"/>
      <!--<logger name="*" writeTo="mail" minlevel="Error"/>-->
    </rules>
  </nlog>

Answer

slolife picture slolife · Jun 17, 2009

Try putting the following in your nlog tag:

<nlog throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Debug" />

That might help determine what the problem is