NLogger每次运行后给出不一致的数据

问题描述 投票:0回答:1

我已经使用NLog在我的代码中记录了函数的入口和出口。但是使用同一应用程序的不同运行,我会得到不同的日志。这是一个多线程应用程序。而且我正在使用异步方式来记录信息。

以下是我的配置:

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

以下是记录器代码。

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

使用Console.Readline(),日志被完全写入,如果没有Console.Readline(),则日志每次都不同如果没有Console.Readline(),则从主线程进行的第三个Print方法调用不会记录任何内容。如果存在Console.Readline(),则第三个打印语句将记录所有信息

c# asynchronous logging nlog
1个回答
0
投票

我想您的句子“我正在获取不同的日志”应翻译为“我缺少一些日志”。

为NLog目标启用异步操作时,刷新很重要,因为写入发生在后台线程上:

NLog.LogManager.Flush()

另请参见:NLog Tutorial - Remember to flush

© www.soinside.com 2019 - 2024. All rights reserved.