Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
          autoReload="true"
          throwExceptions="false"
          internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log" >

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

      <targets>

        <target name="database" xsi:type="Database"
                dbUserName="internwebuser"
                dbProvider="System.Data.SqlClient"
                connectionStringName="SECURE"
                connectionString="Data Source=sqlservtest.starledger.com;Initial Catalog=SECURE;User ID=webuser;Password=password"
                commandText="insert into dbo.tracelog (custom_message, excep_message, insertdate) 
                values 
                (@custom_message, @excep_message, @insertdate);" >


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


        </target>


        <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" />


      </targets>  

      <rules>

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

      </rules>
    </nlog>

And my controller looks something like this:

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

    public ActionResult Index()
    {
        try 
        {
            <!-- some statement -->
        }
        catch (Exception e)
        {
            logger.Error(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 StreamWriter 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 StreamWriter, 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.

My StreamWriter 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);
            }

            else
            {
                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:

            log.Close();

and I pass the method into the catch 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.

like image 470
Bivo Kasaju Avatar asked Mar 02 '16 14:03

Bivo Kasaju


People also ask

Is NLog asynchronous?

NLog 1.0 supports asynchronous logging, but there is no good support for asynchronous exception handling. This is because wrappers targets are not capable of receiving exceptions which are raised on other threads.

What is Basedir in NLog?

${basedir} — Directory where the application runs, aka. AppDomain.BaseDirectory.

Does NLog create directory?

NLog don't create directories for logs #3066.

What is NLog writing?

NLog is “a free logging platform for . NET, Silverlight and Windows Phone with rich log routing and management capabilities. It makes it easy to produce and manage high-quality logs for your application regardless of its size or complexity.”


2 Answers

Please enable internal logging in order to have more info

like image 86
Martino Bordin Avatar answered Oct 13 '22 12:10

Martino Bordin


I faced the same issue.To find the exact issue I added <nlog internalLogFile="c:\DemoLogs\nlog-internal.txt" and internalLogLevel="Error"> inside the nlog tag. which will write the exact proplem to a internal log file (nlog-internal.txt)

For my case Could not load file or assembly 'System.Data.SqlClient was resolve by installing the required nuget package.

like image 43
Sarath Baiju Avatar answered Oct 13 '22 11:10

Sarath Baiju