39

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>
Julian
  • 33,915
  • 22
  • 119
  • 174
Ciaran O'Neill
  • 2,572
  • 6
  • 34
  • 40

2 Answers2

66

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

Julian
  • 33,915
  • 22
  • 119
  • 174
slolife
  • 19,520
  • 20
  • 78
  • 121
  • 10
    ${longdate} was a string that I was trying to insert into a datetime field. Changing it to ${date} did the trick. – Ciaran O'Neill Jun 17 '09 at 16:32
  • Please note, NLog 4.6+ supports Db-types in the database target. So you could set for ${date} , `dbType=DbType.Date`, see https://nlog-project.org/2019/03/20/nlog-4-6-is-live.html – Julian Jun 22 '19 at 22:52
7

NLog allows for logging the internals of the framework itself.

Enable "debug level for your internal logging" for NLog and see what's going wrong.

Sunny Milenov
  • 21,990
  • 6
  • 80
  • 106