简体   繁体   中英

System.Diagnostics.Trace - correct way to log exceptions

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...)

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM