NLog Header(忽略布局)

NLog Header (Ignore layout)

是否可以向日志文件写入一行不是日志的内容?

我想写一个 "Note" 来忽略我的 NLog.config 中的布局,并只写一两行我传递的文本。

这可用于在日志文件上写入 header。

我不确定这是否对解决方案有影响,但我为每个 class 使用单独的 ClassLogger (LogManager.GetCurrentClassLogger()),我无法更改它。

当然可以。将字符串写入以换行符开头的日志。然后写你的内容。

var longMultilineMessage = "pretend this variable contains\n a long multiline message";
logger.Info($"\n{longMultilineMessage}");

将在日志中显示为:

2017-01-01 INFO
pretend this variable contains 
a long multiline message

我能够通过一些创意规则来做到这一点。

首先,在我的代码中,我专门为 header 创建了一个记录器,如下所示:

var loggerNoLayout = LogManager.GetLogger("NoLayout");
loggerNoLayout.Info("<Header Line 1>");
loggerNoLayout.Info("<Header Line 2>");
loggerNoLayout.Info("<Header Line 3>");

然后我像这样修改了我的 NLog.config:

<?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">
    <targets>
        <target name="NoLayout"
                xsi:type="File"
                fileName="${specialfolder:folder=Desktop}\LogFile.log"
                layout="${message}" />
        <target name="FileTrace"
                xsi:type="File"
                fileName="${specialfolder:folder=Desktop}\LogFile.log"
                layout="${level:padding=-5:fixedLength=true} | ${logger:padding=-62:fixedLength=true:alignmentOnTruncation=right}| ${date:format=HH\:mm\:ss} | ${message:padding=-100}"
                deleteOldFileOnStartup="true" />
    </targets>
    <rules>
        <logger writeTo="NoLayout"
                levels="Info"
                name="NoLayout"
                final="true" />
        <logger writeTo="FileTrace"
                minlevel="Trace"
                name="*" />
    </rules>
</nlog>

此处的关键是 NoLayout 目标的布局仅写入消息,并且写入 NoLayout 的规则仅在记录器命名为 NoLayout 时才有效。最后一步是添加 final="true",这样我的普通 (FileTrace) 记录器就不会获取 header 日志。