2015-10-16 43 views
1

NLog沒有使用異步滾動文件記錄器配置來記錄每條日誌消息。NLog缺少具有異步滾動文件配置的日誌條目

以下是我的NLog.config xml。

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

 
    <targets async="true"> 
 
     <target name="logfile" xsi:type="File" fileName="logs/log.txt" 
 
       maxArchiveFiles="10" 
 
       archiveAboveSize="1048576" 
 
       archiveNumbering="Sequence" 
 
       concurrentWrites="true" 
 
       archiveFileName="logs/log.{####}.txt"/> 
 
    </target> 
 
    </targets> 
 

 
    <rules> 
 
    <logger name="*" minlevel="Debug" writeTo="logfile" /> 
 
    </rules> 
 
</nlog>

而下面是我的代碼。

private static Logger log = LogManager.GetCurrentClassLogger(); 
    Stopwatch sw = new Stopwatch(); 

    public Form1() 
    { 
     InitializeComponent(); 
     LogManager.ReconfigExistingLoggers(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     string toLog; 
     sw.Start(); 
     for (int i = 0; i < 100000; i++) 
     { 
      toLog = "Message:" + i.ToString(); 
      log.Debug(toLog); 
     } 
     sw.Stop(); 
     string s = "STOP :" + sw.Elapsed.ToString(); 
     log.Debug(s); 
    } 

我只得到一個文件作爲結果和一些日誌條目丟失。以下是生成的log.txt文件。

2015-10-16 12:04:08.9865|DEBUG|NLogAsync.Form1|Message:11591 
2015-10-16 12:04:08.9865|DEBUG|NLogAsync.Form1|Message:11592 
2015-10-16 12:04:08.9865|DEBUG|NLogAsync.Form1|Message:11593 
2015-10-16 12:04:08.9865|DEBUG|NLogAsync.Form1|Message:11594 
2015-10-16 12:04:09.0802|DEBUG|NLogAsync.Form1|Message:80436 
2015-10-16 12:04:09.0802|DEBUG|NLogAsync.Form1|Message:80437 
2015-10-16 12:04:09.0802|DEBUG|NLogAsync.Form1|Message:80438 
2015-10-16 12:04:09.0802|DEBUG|NLogAsync.Form1|Message:80439 

但是,當我刪除異步屬性,代碼運行正常。

回答

3

<targets async="true">只是一個簡寫,用於將所有目標換成AsyncWrapper目標。即您的配置相當於:

<targets> 
    <target name="logfile" xsi:type="AsyncWrapper"> 
    <target xsi:type="File" fileName="logs/log.txt" 
      maxArchiveFiles="10" 
      archiveAboveSize="1048576" 
      archiveNumbering="Sequence" 
      concurrentWrites="true" 
      archiveFileName="logs/log.{####}.txt"/> 
    </target> 
</targets> 

此異步包裝將使用默認設置。最重要的是queueLimit默認爲10000,而overflowAction默認爲Discard。這是什麼意思?編寫器線程在隊列中有超過10000條日誌消息後,所有新的日誌消息都被丟棄。確保處理所有日誌消息的最簡單方法是將默認overflowAction值更改爲Grow。但是您需要手動指定AsyncWrapper

<targets> 
    <target name="logfile" xsi:type="AsyncWrapper" overflowAction="Grow"> 
    <target xsi:type="File" fileName="logs/log.txt" 
      maxArchiveFiles="10" 
      archiveAboveSize="1048576" 
      archiveNumbering="Sequence" 
      concurrentWrites="true" 
      archiveFileName="logs/log.{####}.txt"/> 
    </target> 
</targets>