Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Diagnostics.Trace - correct way to log exceptions

Tags:

c#

.net

azure

I'm using the Trace class from an Azure Worker Role.

I want to log exceptions in a way that will print all the information about the exception which is usually:

  • The exception message
  • Exception stacktrace
  • Recursively print the inner exceptions

I only see a Trace.TraceError method that gets a string and arguments. Isn't there something equivalent to Java's logging frameworks that gets an exception and know how to log it? (yes, I am doing my first steps in MS world...)

like image 647
daramasala Avatar asked Dec 25 '14 08:12

daramasala


People also ask

What is system diagnostics trace?

Tracing helps you isolate problems and fix them without disturbing a running system. This class provides methods to display an Assert dialog box, and to emit an assertion that will always Fail. This class provides write methods in the following variations: Write.

Where does system diagnostics trace WriteLine write to?

WriteLine(String) Writes a message to the trace listeners in the Listeners collection.

What is system Diagnostics C#?

Diagnostics provides a set of attributes and classes to interact with the system process, event managers, performance counts, etc. This namespace can help us too in debugging jobs. Let's review the useful actions inside System. Diagnostics namespace.


1 Answers

No, there isn't. But you could write an extension method for the Exception class that does this so you could call

someException.Trace();

The ToString method of the Exception class probably returns all you want so just Trace that. You could add additional information (recurse inner exceptions if the stack trace isn't sufficient) process id, user id, thread id, and such in that same method.

public static class ExceptionExtensions
{
    public static void Trace(this Exception _this)
    {
        Trace.TraceError("{0:HH:mm:ss.fff} Exception {1}", DateTime.Now, _this);
    }
}
like image 157
Emond Avatar answered Oct 06 '22 23:10

Emond