Tasheer Hussain
Tasheer Hussain

Reputation: 25

NLogger giving inconsistent data after each run

I have used NLog to log the entry and exits of functions in my code. But with different runs of the same Application I am getting different logs. It is a multi threaded application. And I am using async to log the information.

The following is my configuration:

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

  <targets>
    <target name="asynclogger" xsi:type="AsyncWrapper" overflowAction="Grow" queueLimit="100000" batchSize="5000" timeToSleepBetweenBatches="1">
      <target name="logfile" xsi:type="File" fileName="D:\IALogs\${processname}_${processid}_${threadid}.ialog"  layout ="${longdate} ${processname} ${processid} ${threadid} ${mdlc:item=threadid} ${level} ${message}"/>
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="asynclogger" />
  </rules>
</nlog>

The following is the logger code.

class Program
    {
        private static readonly NLog.Logger nLogger = NLog.LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {
            Thread th1 = new Thread(() => print(5000000));
            th1.Start();

            Thread th2 = new Thread(() => print(5000000));

            th2.Start();

            th1.Join();
            th2.Join();

            print(10000);

            Console.WriteLine("Done!!!!");
            Console.ReadLine();
        }

        private static void print(int noOfItems)
        {
            for (int i = 1; i <= noOfItems; i++)
            {
                nLogger.Info("Printing i =" + i);
            }
        }
    } 

With Console.Readline() the logs are completely written, if there is no Console.Readline() the logs are different each time and also the third Print method call from the main thread doesn't log anything if there is no Console.Readline(). If Console.Readline() is present then the 3rd print statement logs all the information

Upvotes: 1

Views: 319

Answers (1)

Rolf Kristensen
Rolf Kristensen

Reputation: 19867

I guess your sentence "I am getting different logs" should be translated to "I am missing some logs".

When enabling async-operations for NLog targets, then it is important to flush, because writing happens on background threads. Must wait for these, before exiting the application:

NLog.LogManager.Flush()

See also: NLog Tutorial - Remember to flush

Upvotes: 2

Related Questions