为什么NLog在记录大量消息时会遗漏一些消息?

Boo*_*Boo 9 .net c# logging nlog

我尝试使用以下设置测试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" autoReload="true">
    <variable name="basePath" value="c:\logs\" />
    <variable name="msgFormat" value="${message}" />
    <targets async="true">
        <target name="file"
                xsi:type="File"
                fileName="${basePath}/${logger}/${date:format=yyyy}/${date:format=MMMM}/log-${date:format=yyMMdd}-${level}.log"
                layout="${msgFormat}"
                concurrentWrites="true" />
    </targets>
    <rules>
        <logger name="*" minlevel="Debug" writeTo="file"/>
    </rules>
</nlog>
Run Code Online (Sandbox Code Playgroud)

并运行此代码:

var msg = "this is example string for logging test. it's not very long, but not very short";
var count = 20000;
Parallel.For(0, count, x => nlog.Info(msg));
Run Code Online (Sandbox Code Playgroud)

NLog写入文件,但当文件大小达到1MB时,它将停止写入.我尝试使用简单的for循环,但它没有帮助我.我尝试使用内部日志记录,但没有错误,顺便说一下,我看到这个字符串:

2013-04-01 11:36:18.2458跟踪打开c:\ logs/NLogTest/2013/April/log-130401-Info.log with concurrentWrite = False

这很奇怪,因为concurrentWrites默认值是true,而且我在config中设置了这个值.

Xha*_*rze 8

问题在于AsyncWrappers 的默认值QueueLimit,即10000.

该值确定允许写入的消息队列的大小,问题出现是因为在将任何内容写入文件之前所有20000条消息都排队,这导致NLog丢弃最后10000条消息.

不幸的是,在使用async属性时无法更改,您必须AsyncWrapper手动定义才能控制QueueLimit,这样做:

<?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" autoReload="true">
    <variable name="basePath" value="c:\logs\" />
    <variable name="msgFormat" value="${message}" />
    <targets async>
        <target name="asyncWrapper" xsi:Type="AsyncWrapper" queueLimit="20000">
            <target name="file"
                xsi:type="File"
                fileName="${basePath}/${logger}/${date:format=yyyy}/${date:format=MMMM}/log-${date:format=yyMMdd}-${level}.log"
                layout="${msgFormat}"
                concurrentWrites="true" />
       </target>
    </targets>
    <rules>
        <logger name="*" minlevel="Debug" writeTo="file"/>
    </rules>
</nlog>
Run Code Online (Sandbox Code Playgroud)

其中QueueLimit设置为20000.

您还可以更改OverflowAction如果您需要执行其他未放入队列的丢弃消息,请参阅AsyncWrapper文档以获取更多信息.选项包括Block,Discard或Grow.