Bivo Kasaju Bivo Kasaju - 1 year ago 188
SQL Question

NLog is writing to file but not to database table

This is my NLog.config file:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns=""
xsi:schemaLocation=" NLog.xsd"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log" >

<variable name="myvar" value="myvalue"/>


<target name="database" xsi:type="Database"
connectionString="Data;Initial Catalog=SECURE;User ID=webuser;Password=password"
commandText="insert into dbo.tracelog (custom_message, excep_message, insertdate)
(@custom_message, @excep_message, @insertdate);" >

<parameter name="@custom_message" layout="${exception}" />
<parameter name="@excep_message" layout="${exception:tostring}" />
<parameter name="@insertdate" layout="${date}" />


<target name="file" xsi:type="File"
layout="${longdate} ${uppercase:${level}} ${callsite} from Line: ${callsite-linenumber} ${newline}
${exception} ${newline}
${exception:tostring} ${newline}"
fileName="${basedir}/logs/${shortdate}-${level}.log" />



<logger name="*" minlevel="Debug" writeTo="file" />
<logger name="*" minlevel="Debug" writeTo="database" />


And my controller looks something like this:

public class ReportController : Controller
private static Logger logger = LogManager.GetCurrentClassLogger();

public ActionResult Index()
<!-- some statement -->
catch (Exception e)
return View();

This code writes perfectly into the file but the database table remains empty. Also, in my file, when I do it using
and create a file instead of using NLog, the application writes 2/3 kinds of error into the file simultaneously. But NLog only writes the last error.

For example:

In case of
, the errors are:

Exception Name:ExecuteReader requires an open and available Connection. The connection's current state is closed.

Exception Name:Object reference not set to an instance of an object.

But In case of NLog, I only get:

Exception Name:Object reference not set to an instance of an object.
and the first one is missed out.

method looks like this:

DateTime today = DateTime.Now;

string path = Directory.GetCurrentDirectory();

string fileName = "error-log-" + today.Date.ToString("MM-dd-yyyy") + ".txt";

var file = Path.Combine(path, fileName);

StreamWriter log;

if (!File.Exists(file))
log = new StreamWriter(file);

log = File.AppendText(file);

// Write to the file:

log.WriteLine("Data Time:" + DateTime.Now);
log.WriteLine("Exception Name:" + sExceptionName);
log.WriteLine("Event Name:" + sEventName);
log.WriteLine("Error Line No.:" + nErrorLineNo);

// Close the stream:


and I pass the method into the
section of my controller.

My main issue here is writing into the database table, although I'd appreciate help in writing all the errors too, using Nlog, instead of just the last one.

Answer Source

Please enable internal logging in order to have more info

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download