Writing stack trace to log file only when throwing exception

I want to write a stack trace only when I have exceptions, currently I am doing it like this:

layout="${longdate}|${level}|${message} ${exception:format=tostring} | ${stacktrace}" 

Therefore, I always get it in my log file.

EDIT:

I use this layout for all my logging, so when I don't have any exceptions, I also get a stack trace. But I need this only when I have some kind of exception.

when I have an exception, I have the following conclusion, and this is what I need

 2011-07-01 22:59:02.3782|Debug|fffffffffffffffffffffffffffff System.Exception: Exception of type 'System.Exception' was thrown. | AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main 

But without exception:

 2011-07-01 22:57:26.7117|Trace|fffffffffffffffffffffffffffff | AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main 

But I only want

 2011-07-01 22:57:26.7117|Trace|fffffffffffffffffffffffffffff 

Need ideas how to do this ...

+7
source share
2 answers

Yes, in NLog you can use different levels of Warn, Error Info, etc. You can also throw exceptions with ErrorException, WarnException, InfoException. IE

 logger.Error("This is an error message"); 

If you want to show an exception, use the following.

 logger.ErrorException("This is an error with an Exception", e); 

Update:

 <target name="Errors" xsi:type="File" fileName="${logDirectory}/ErrorLog.txt" layout="${longdate} ${message} ${exception:format=tostring}"/> 

Delete {stacktrace}

Update:

 Exception e = new Exception(); e.StackTrace // <= The exception holds the stack trace 

You will get a stack from the exception.

+2
source

you can use the following layout:

 ${longdate}|${level}|${message} ${onexception:${exception:format=tostring} | ${stacktrace}} 
+13
source

All Articles