Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NLog Header (Ignore layout)

Tags:

c#

logging

nlog

Is is possible to write a line to the log file that's not a log?

I'd like to write a "Note" that will ignore the layout in my NLog.config and just write the text exactly as I pass it for one or two lines.

This could be used for writing a header on the log file.

I'm not sure if this will matter to the solution but I'm using a separate ClassLogger (LogManager.GetCurrentClassLogger()) for every class and it's not an option for me to change that.

like image 249
LorneCash Avatar asked Aug 30 '25 18:08

LorneCash


1 Answers

I was able to do this with a few creative rules.

First in my code I created a logger specifically for the header like this:

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

Then I modified my NLog.config like this:

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

The key here is that the NoLayout target's layout only writes the message and the rule for writing to NoLayout only works if the logger is named NoLayout. The final step is to add the final="true" so that my normal (FileTrace) logger does not pick up the header logs.

like image 156
LorneCash Avatar answered Sep 02 '25 08:09

LorneCash