Domanda

I have problem log exception only message is logged.

NLog config:

<target name="logfile"
        xsi:type="File"
        fileName="log.txt"
        layout="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | |${message} | ${exception:format=tostring}" />



<logger name="*"
        minlevel="Info"
        writeTo="logfile" />

Usage:

    private static Logger _logger = LogManager.GetCurrentClassLogger();

    _logger.Error("my message", new Exception("my exception"));

Log output:

2014-04-24 18:17:29.0841 | PC_NAME | 6464 | APP_NAME.vshost | Error | AppName.ViewModel | my message |

Exception is ignore.

I found some thread but for me not work.

È stato utile?

Soluzione

Nlog is using sepecial methods for logging exceptions which are using the <loglevel>Exception naming schema.

So in your case you need to use the ErrorException method in order to your exceptions get logged correctly:

private static Logger _logger = LogManager.GetCurrentClassLogger();

_logger.ErrorException("my message", new Exception("my exception"));

Altri suggerimenti

Actually, void Error(string message, Exception exception); is obsolete

You can use ILogger.Error(Exception, string) method like below

catch (Exception e)
{
 Log.Error(e, "it happens");
}

and a little bit modified layout with ${onexception}. This will check is there an exception to be logged

<target name="logfile"
        xsi:type="File"
        fileName="log.txt"
        layout="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | |${message} ${onexception:| ${exception:format=tostring}}" />

/>

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top