Please note I am answering my own question to help people in the future.
When I use NLog to log to a trace target type, it only works correctly if the level is Trace
or Debug
. If it's Info
, Warn
, or Error
, it prepends extra info before my layout. If the level is Fatal
, I get a pop-up complaining about a failed assertion and it says so in the output too. Is the trace target bugged?
Program.cs
using System;
namespace TraceLoggingTest
{
class Program
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
logger.Trace("Hello Trace");
logger.Debug("Hello Debug");
logger.Info("Hello Info");
logger.Warn("Hello Warn");
logger.Error("Hello Error");
logger.Fatal("Hello Fatal");
Console.ReadLine();
NLog.LogManager.Shutdown();
}
}
}
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"
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>
<target name="logTrace" xsi:type="Trace" layout="${message}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="logTrace" />
</rules>
</nlog>
Expected output
Hello Trace
Hello Debug
Hello Info
Hello Warn
Hello Error
Hello Fatal
Actual output
Hello Trace
Hello Debug
TraceLoggingTest.exe Information: 0 : Hello Info
TraceLoggingTest.exe Warning: 0 : Hello Warn
TraceLoggingTest.exe Error: 0 : Hello Error
---- DEBUG ASSERTION FAILED ----
---- Assert Short Message ----
Hello Fatal
---- Assert Long Message ----
A fix for the prepending issue was introduced in Nlog 4.5. You need to add rawWrite="true"
to the target statement. It also happens to fix the assertion problem.
Change:
<target name="logTrace" xsi:type="Trace" layout="${message}" />
To this:
<target name="logTrace" xsi:type="Trace" layout="${message}" rawWrite="true" />
From https://github.com/NLog/NLog/wiki/Trace-target :
Layout Options
rawWrite - Always use
Trace.WriteLine
independent of LogLevel.Default: False
Introduced with NLog 4.5, fixes the issue with output being prefixed with exe-filename.
Here are two discussions of the original problem:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.