2

Possible Duplicate:
How do I in java add a stacktrace to my debugging printout

What's the best way to include the stack trace in log4j's output when there's not an exception? The only way I can think of is to create a new Exception instance.

log.error("description", new Exception());

Follow-up: I am fully aware of Thread.currentThread().getStackTrace() and Thread.dumpStack(). These output to the console, which in many environments are separate from the log4j output. What I'm looking for a way to log the stack trace to log4j, and not the console.

Community
  • 1
  • 1
Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
  • Do you want the stack trace of the current thread? – davidbuzatto Oct 10 '12 at 18:23
  • What is missing from the two solutions you provided by yourself? "doesn't do me any good" is not a very constructive comment. – Maarten Bodewes Oct 10 '12 at 20:58
  • This is not a duplicate of http://stackoverflow.com/questions/54882. This question asks how to include the stack trace in **log4j**. The "duplicate" question merely outputs the stack trace to standard out. Standard out != log4j output. – Steve Kuo Oct 11 '12 at 23:31
  • @owlstead I want the stack trace in the log4j output and not standard out. – Steve Kuo Oct 11 '12 at 23:34

1 Answers1

-1

Steve, I understood that you want the stack trace of the current thread. If so, you can get it by using the currentThread() static method of the Thread class and then getting the stack trace. Something like:

StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();

If you want to dump the stack traces of all running threads, you can use the getAllStackTraces() static method of the Thread class.

Map<Thread,StackTraceElement[]> stackTraces = Thread.getAllStackTraces();

Update

Steve, I tried the dumpStack() static method of Thread class and it uses an empty exeption to perform the dump, so, I think that the way you are doing is correct, or "the best way".

davidbuzatto
  • 9,207
  • 1
  • 43
  • 50