Reputation: 6579
I am trying to figure out why NLog logs my error twice.
here is my config file:
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="debug" xsi:type="File" FileName="DebugTestFile.log" layout="${message} ${exception:format=tostring}" />
</targets>
<rules>
<logger name="*" level="Debug" writeTo="debug" />
</rules>
</nlog>
Now when I call NLog.Debug(myException);
the output is my exception gets printed twice.
If I call NLog.Debug(myException, "My Test Message String");
then the error gets printed out once along with my test message.
What exactly am I doing wrong? According to https://github.com/NLog/NLog/wiki/How-to-Log-Exceptions my configuration is correct.
I tried changing my layout to the following: layout="${message}
and when I ran NLog.Debug(myException);
it only printed the error once.
However now when I ran NLog.Debug(myException, "My Test Message String");
it only printed my message without the error that comes from exception.
Could this be a bug with NLog?
Upvotes: 5
Views: 5232
Reputation: 19867
NLog Logger-method Error<T>(T value)
is shorthand for Error("{0}", value)
.
This means the ${message}
output becomes string.Format("{0}", value)
or value.ToString()
, which is the original behavior.
NLog have over time tried to improve the handling of Exception
-object as value:
But yes a workaround is calling Logger.Error(ex, "")
, then ${message}
will output empty-string ""
.
Alternative with NLog v4.6 (and newer) then one can use ${message:withException=true}
instead of ${message} ${exception:format=tostring}
Upvotes: 0
Reputation: 19867
Updated Answer
NLog.Web.AspNetCore v4.8.6 changes registration of NLog Logging Provider, so one is now allowed to call both AddNLog
and UseNLog
without experiencing double logging.
NLog 5.0 implements validation of incorrect duplicate target configuration, so one will not experience double logging when using incorrect NLog configuration.
Original Answer
If you are using NLog in AspNetCore, then the problem can be caused by calling UseNLog
together with AddNLog
or ConfigureNLog
.
You should only use UseNLog
together with NLog.Web.LogBuilder.ConfigureNLog
(Stop using AddNLog
):
https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-2#4-update-programcs
Upvotes: 17
Reputation: 3914
This is seems to be because of rule in config file, just change writeTo for each logger, in my case I was able to reolve this issue by following same steps:
Example:
Earlier config file which was having issue:
<rules>
<logger name="*" minlevel="Info" writeTo="console" />
<logger name="*" minlevel="Error" writeTo="console" />
</rules>
Corrected config file:
<rules>
<logger name="*" minlevel="Info" writeTo="console" />
<logger name="*" minlevel="Error" writeTo="console1" />
</rules>
Upvotes: 1