Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to log Exceptions to a string

Tags:

c#

.net

Anyone have a good way to output an Exception in C# to a string that handles inner exceptions and the such? I am sure every developer has her own implimentation of this, but I can't find my old one and want to see what better ones are out there.

Here is one without recursion for inner exceptions as an example:

var Message = String.Format("Exception Message: \n{0}\n\nStackTrace: \n{1}", ex.Message, ex.StackTrace);
like image 581
JasonRShaver Avatar asked Jul 20 '09 20:07

JasonRShaver


People also ask

How do I log an exception?

To log a handled exceptionCreate the method that will generate the exception information. Use a Try...Catch block to catch the exception. Put the code that could generate an exception in the Try block. Uncomment the Dim and MsgBox lines to cause a NullReferenceException exception.

How do you log an exception in Python?

Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger.

Should you log before throwing exception?

Log it when you handle it So, better only log the exception when you handle it. Like in the following code snippet. The doSomething method throws the exception. The doMore method just specifies it because the developer doesn't have enough information to handle it.

Should I log stack trace?

Therefore, you should log a stacktrace if, and only if, and always if, the exception indicates a bug in the program. However, that does not always indicate that a method you write should catch and log the exception.


1 Answers

Simply method ToString is the best:

ex.ToString();
like image 82
Michał Ziober Avatar answered Oct 21 '22 08:10

Michał Ziober