简体   繁体   English

System.Diagnostics.Trace - 记录异常的正确方法

[英]System.Diagnostics.Trace - correct way to log exceptions

I'm using the Trace class from an Azure Worker Role. 我正在使用Azure辅助角色中的Trace类。

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. 我只看到一个获取字符串和参数的Trace.TraceError方法。 Isn't there something equivalent to Java's logging frameworks that gets an exception and know how to log it? 是不是有一些等同于Java的日志记录框架的东西得到异常并且知道如何记录它? (yes, I am doing my first steps in MS world...) (是的,我正在MS世界中迈出第一步......)

No, there isn't. 不,没有。 But you could write an extension method for the Exception class that does this so you could call 但是你可以为Exception类编写一个扩展方法来执行此操作,以便调用

someException.Trace();

The ToString method of the Exception class probably returns all you want so just Trace that. Exception类的ToString方法可能会返回您想要的所有内容,因此只需跟踪它。 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. 您可以添加其他信息(如果堆栈跟踪不充分,则递归内部异常)进程ID,用户ID,线程ID等在同一方法中。

public static class ExceptionExtensions
{
    public static void Trace(this Exception _this)
    {
        Trace.TraceError("{0:HH:mm:ss.fff} Exception {1}", DateTime.Now, _this);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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