我想根据条件将消息记录到文件中。为此,我首先将所有日志消息写入“内存类型”,然后在后面的代码中检查条件。我试图写入文件类型,仅当条件为true时,那些堆积的(内存)日志才会写入。这是我的日志的样子。
<targets>
<target name="file" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
<!--auto-archive above 5 MB or daily. Max archives = 3 days
write to <installdir>/logs/DebugLog.log-->
<target xsi:type="File" name="debugFile" fileName="${basedir}/logs/DebugLog.log"
layout="${message}"
archiveFileName="${basedir}/logs/archives/DebugLog-${shortdate}.{#}.txt"
archiveAboveSize="5242880"
archiveEvery="Day"
archiveNumbering = "Rolling"
maxArchiveFiles="3" />
</target>
<target xsi:type="Memory" name="MemoTarget" layout="${longdate} : ${message}"/>
</targets>
<rules>
<!-- turn logging on by setting minLevel="Debug" (no service restart necesary, it detects the setting change automatically) -->
<logger name="*" minlevel="Debug" writeTo="MemoTarget"/>
<logger name="MyFileLogger" minlevel="Debug" writeTo="debugFile"/>
</rules>
这是背后的代码。
if (dTimeRTaken > 7000)
{
StringBuilder stringBuilder = new StringBuilder();
var target = (MemoryTarget)LogManager.Configuration.FindTargetByName("MemoTarget");
var logger = LogManager.GetLogger("MyFileLogger");
foreach (var loggingEvent in target.Logs.ToArray())
{
stringBuilder.AppendLine(loggingEvent);
}
logger.Debug(stringBuilder);
LogManager.Flush();
}
这里的问题是刷新不起作用,并且附加了内存目标消息。文件内容就像
1
12
123
1234
我希望输出为1 2 3 4
答案 0 :(得分:1)
也许在文件目标周围使用BufferingWrapper。像这样:
<targets>
<target name="memoFile" xsi:type="BufferingWrapper" bufferSize="10000" overflowAction="Discard">
<target name="asyncFile" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
<target name="debugFile" xsi:type="File" fileName="${basedir}/logs/DebugLog.log">
</target>
</target>
</target>
</targets>
<rules>
<!-- MyFileLogger writes directly to file without being stalled in buffer -->
<logger name="MyFileLogger" minlevel="Debug" writeTo="asyncFile" final="true" />
<!-- All other loggers writes to memory buffer and waits for flush -->
<logger name="*" minlevel="Debug" writeTo="memoFile" final="true" />
</rules>
但是,如果您想在不使用BufferingWrapper的情况下手动控制日志事件,则应该确保配置日志记录规则,如下所示:
<rules>
<!-- MyFileLogger writes directly to file without being stalled in buffer -->
<logger name="MyFileLogger" minlevel="Debug" writeTo="asyncFile" final="true" />
<!-- All other loggers writes to memory buffer and waits for flush -->
<logger name="*" minlevel="Debug" writeTo="MemoTarget" final="true" />
</rules>