NLog Mail Target无法使用BufferingWrapper \ PostFilteringWrapper

时间:2016-01-19 10:20:36

标签: c# .net email nlog

我想通过电子邮件发送失败的日志。但是,如果我直接使用邮件目标而没有BufferingWrapper& PostFilteringWrapper(目标:mailLog3),然后我为每个日志条目获得一个单独的电子邮件。如果我使用BufferingWrapper& PostFilteringWrapper(目标:mailLog1),这有时是第一次,但不是第二次。

<configuration>
  <configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    throwExceptions="true" internalLogToConsole="true" internalLogLevel="Warn" internalLogFile="nlog.log">

<variable name="Error" value="Logs\${shortdate}_ErrorLog.xml"/>

<targets async="true">
  <!--The following will keep the default number of log messages in a buffer and write out certain levels if there is an error and other levels if there is not. Messages that appeared before the error (in code) will be included, since they are buffered.-->
  <wrapper-target xsi:type="BufferingWrapper" name="smartLog">
    <wrapper-target xsi:type="PostFilteringWrapper">
      <!--<target-ref name="fileAsCsv"/>-->
      <target xsi:type="File" fileName="${Error}"
      archiveAboveSize="4194304" concurrentWrites="false" maxArchiveFiles="1" archiveNumbering="Sequence">
        <layout xsi:type="Log4JXmlEventLayout">
        </layout>
      </target>

      <!--during normal execution only log certain messages-->
      <defaultFilter>level >= LogLevel.Warn</defaultFilter>

      <!--if there is at least one error, log everything from trace level-->
      <when exists="level >= LogLevel.Error" filter="level >= LogLevel.Trace" />
    </wrapper-target>
  </wrapper-target>

  <wrapper-target xsi:type="BufferingWrapper" name="mailLog1" slidingTimeout="true" bufferSize="1000" flushTimeout="-1">
    <wrapper-target xsi:type="PostFilteringWrapper" name="mailLog2" defaultFilter="level = LogLevel.Fatal">
      <target xsi:type="Mail" name="mailLog3"
                smtpServer="xxx"
                smtpPort="25"
                smtpAuthentication="None"
              subject="Error"
                from="xxx"
                to="xx"
                layout="${longdate} ${uppercase:${level}} ${callsite:className=true:includeSourcePath=true:methodName=true} ${message}${newline}" />
      <when exists="level = LogLevel.Fatal" filter="level >= LogLevel.Trace"/>
    </wrapper-target>
  </wrapper-target>


</targets>
<rules>
  <logger name="*" minlevel="Trace" writeTo="smartLog"/>
  <logger name="*" minlevel="Trace" writeTo="mailLog1"/>
</rules>
</nlog>
</configuration>

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

如果在BufferingWrapper上将slidingTimeout设置为true(在这种情况下是默认值),则消息已经异步写入。

因此不需要将BufferingWrapper与async属性或AsyncWrapper结合使用。正如您所注意到的,将BufferingWrapper与异步写入相结合可能会导致丢失消息。这是因为在异步编写中,消息被写入另一个异步编写器。

See documentation of the BufferingWrapper

答案 1 :(得分:0)

我发现了问题。如果我设置:

<targets async="false">

它运作正常。有趣的是在其他项目中,这也适用于:

<targets async="true">