Generate a Java stacktrace at any point in the program

Possible Duplicate:
Get current stack trace in Java

I have a method that saves messages to a file. This method is called from many different parts of my main program. Is there any way that I can generate the stack trace on demand, even though an Exception hasn't been triggered?

For example, I was hoping for something like this...

void saveMsg(String Msg)
{
  if (a==b) Print Out Where This Method Was Called From [ like stackTrace in exception ]
  else saveMsgToFile(filePath,Msg);
}

I know Java can stack trace in an Exception , but how can I generate the stack trace when no Exception has occurred?


Just do Thread.dumpStack() , this will print the stack trace to the console. There's no need to mess with creating an exception and catching it.


You can generate your own Exception and capture the result...

try {
    throw new Exception("Tracing only");
}
catch (Exception e){
    e.printStackTrace();
}

Put this code anywhere you want to output a stack trace.

The benefit of doing it this way is that the e.printStackTrace(); method handles the output nicely for you, assuming you want to output to the console. By triggering an Exception , you can also specify a text string for the cause (in this example, "Tracing only" ), so you can easily customise the trace output with a meaningful header, such as "Tracing the saveMsg method" .

Alternatively you can get the stack trace itself by calling this...

Thread.currentThread().getStackTrace();

However this leaves you with an array of StackTraceElement s that you have to loop over to output. In my opinion, its easier and cleaner to just generate and catch your own Exception , as in the first option.


Unfortunately, only

    Thread.currentThread().getStackTrace();

useful for your task. The problem is that all earlier mentioned approaches will print your method (saveMsg) on the top of the stack, but it is generally not desirable. Instead, you will have to skip the first element returned from getStackTrace() method.

链接地址: http://www.djcxy.com/p/82408.html

上一篇: 使用throws Exception获取函数的堆栈跟踪

下一篇: 在程序中的任何位置生成Java堆栈跟踪