如何检查NLog在异步模式下是否已完成日志记录队列中的消息?

4
我有一个如下的NLog配置文件。由于某些原因,NLog需要进行异步处理。
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  autoReload="true">
  <targets async="true">
    <target name="file" xsi:type="File" fileName="c:/log1.log" archiveEvery="Day" archiveNumbering="Rolling"/>
  </targets>
  <rules>
     <logger name="*" minlevel="Info" writeTo="file"/>
  </rules>
</nlog>

我想知道是否有一种方法可以用来检查NLog是否完成了日志记录,类似下面这样的:

for (int i = 0; i <= 9999; i++)
{
    LogManager.GetCurrentClassLogger().Info("this is for testing " + i);
}
while(!LogManager.finished())  // check if finished or not
{
    Console.Write(".");
}
Console.Write("done");

Thanks.

Look

1个回答

1

虽然没有布尔值可供检查,但您可以调用flush函数-当该调用完成时,日志记录就结束了。

例如:

for (int i = 0; i <= 9999; i++)
{
    LogManager.GetCurrentClassLogger().Info("this is for testing " + i);
}
LogManager.Flush(); //flushes all async targets and block until done. There is also an optional timeout.
Console.Write("done");

请参见LogManager方法


@llook 这是你在寻找的地方吗? - Julian
LogManager.Flush() 不会同步等待,因此我们无法保证在关闭应用程序之前所有日志都被正确记录。 - Vikram Singh
Flush是同步的。请参见代码。但是由于存在超时,没有任何保证。(可以手动设置超时时间) - Julian
Flush看起来是同步的,但它只是调用一些内部代码来告诉系统完成挂起的消息,但它并不等待所有消息都被完成,因此从内部来看它似乎是异步的。 - Vikram Singh
是的,因为有超时限制。 - Julian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接