Log stack trace java exception

How to print an exception stack trace using Log4J (or Commons Logging)

Printing the stack trace of a Log4J exception seems to be something of a trick question. In reviewing Java code from different developers at different organizations I see a lot of people working very hard to print a stack trace using Log4J, including a lot of variations of calling e.printStackTrace() method. In this short tutorial I’ll show how to solve this problem.

Log4J exception stack trace — short answer

The short answer is that all you have to do to print the stack trace of an exception using Java and Log4J (or the Apache Commons Logging project) is this:

log.error("Your description here", exception);

where exception is your Java Exception object. The Log4j error method that takes a description followed by a Throwable will print the stack trace of the Java Throwable object.

For more information on how this works with Log4J I recommend looking at the API documentation for the Logger class.

A more complete Log4J exception stack trace example

In case that isn’t clear, the following source code might help to make what I’m saying more clear:

In these Log4j exception printing examples, the variable named log refers to my Log4J logger reference, which I create somewhere earlier in the code.

Of course if you’re using the Log4j warn or debug methods you’ll just call those methods instead of the error method. Here’s a Log4j debug method example:

log.debug("Your description here", exception);

and here’s the Log4j warn method syntax:

log.warn("Your description here", exception);

As I wrap up my current collection of Log4J examples, here’s a link to my other Log4J tutorials:

Источник

Java — How to output stack trace (Throwable, Exception)

In Java, you can output the callstack as a Throwable object. Stack trace shows which functions have passed through to the current code position.

You can get or print Trace using the following methods of Throwable.

// Throwable.java public void printStackTrace() public void printStackTrace(PrintStream s) public StackTraceElement[] getStackTrace()

If you look at the Java code, the Exception class inherits the Throwable class. That s why Exception objects can also use Throwable s methods.

public class Exception extends Throwable  ... >

Usually, exceptions are handled using the try-catch pattern. Here, if Exception.printStackTrace() is called, a stack trace is output to the log.

try  Exception e = new Exception(); e.initCause(new IOException("No space memory")); throw e; > catch(Exception e)  e.printStackTrace(); >
java.lang.Exception at example.StackTrace$AAA.ccc(StackTrace.java:21) at example.StackTrace$AAA.bbb(StackTrace.java:14) at example.StackTrace$AAA.aaa(StackTrace.java:10) at example.StackTrace.main(StackTrace.java:47) Caused by: java.io.IOException: No space memory at example.StackTrace$AAA.ccc(StackTrace.java:22) . 3 more

Throwable also supports printStackTrace(PrintWriter s) method.

You can add a Trace to a PrintWriter by passing a PrintWriter as an argument as follows:

try  Exception e = new Exception(); e.initCause(new IOException("No space memory")); throw e; > catch(Exception e)  StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.append("+++Start printing trace:\n"); e.printStackTrace(pw); pw.append("---Finish printing trace"); System.out.println(sw.toString()); >
+++Start printing trace: java.lang.Exception at example.StackTrace$AAA.fff(StackTrace.java:50) at example.StackTrace$AAA.bbb(StackTrace.java:22) at example.StackTrace$AAA.aaa(StackTrace.java:12) at example.StackTrace.main(StackTrace.java:75) Caused by: java.io.IOException: No space memory at example.StackTrace$AAA.fff(StackTrace.java:51) . 3 more ---Finish printing trace

Output stack trace without exception

The above codes can only be used when an Exception occurs.

If you just want to print a trace for debugging purposes, create a Throwable object as shown below and call printStackTrace() . It s not a throw`, so only the log is output and the object is destroyed.

// print stack trace (new Throwable()).printStackTrace();
java.lang.Throwable at example.StackTrace$AAA.eee(StackTrace.java:39) at example.StackTrace$AAA.bbb(StackTrace.java:16) at example.StackTrace$AAA.aaa(StackTrace.java:10) at example.StackTrace.main(StackTrace.java:47)

Import as String without outputting trace

You can get the Trace as a String object without outputting it to the log.

When getStackTrace() is called as shown below, StackTraceElement array is returned. StackTraceElement object holds trace information, and the more stacks are stacked, the longer the array length. You can output the items of this object as a String.

// get stack trace and print StackTraceElement[] stacks = (new Throwable()).getStackTrace(); for (StackTraceElement element : stacks)  System.out.println(element); >
example.StackTrace$AAA.ddd(StackTrace.java:31) example.StackTrace$AAA.bbb(StackTrace.java:15) example.StackTrace$AAA.aaa(StackTrace.java:10) example.StackTrace.main(StackTrace.java:47)

The code below is the code used as an example above.

package example; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; public class StackTrace  static class AAA  void aaa()  bbb(); > void bbb()  ccc(); sleep(1000); ddd(); sleep(1000); eee(); sleep(1000); fff(); > void ccc()  try  Exception e = new Exception(); e.initCause(new IOException("No space memory")); throw e; > catch(Exception e)  e.printStackTrace(); > > void ddd()  // get stack trace and print StackTraceElement[] stacks = (new Throwable()).getStackTrace(); for (StackTraceElement element : stacks)  System.out.println(element); > > void eee()  // print stack trace (new Throwable()).printStackTrace(); > void fff()  try  Exception e = new Exception(); e.initCause(new IOException("No space memory")); throw e; > catch(Exception e)  StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.append("+++Start printing trace:\n"); e.printStackTrace(pw); pw.append("---Finish printing trace"); System.out.println(sw.toString()); > > void sleep(long ms)  try  Thread.sleep(ms); > catch (InterruptedException e)  e.printStackTrace(); > > > public static void main(String args[])  AAA a = new AAA(); a.aaa(); > >
  • Java — Remove items from List while iterating
  • Java — How to find key by value in HashMap
  • Java — Update the value of a key in HashMap
  • Java — How to put quotes in a string
  • Java — How to put a comma (,) after every 3 digits
  • BiConsumer example in Java 8
  • Java 8 — Consumer example
  • Java 8 — BinaryOperator example
  • Java 8 — BiPredicate Example
  • Java 8 — Predicate example
  • Java 8 — Convert Stream to List
  • Java 8 — BiFunction example
  • Java 8 — Function example
  • Java — Convert List to Map
  • Exception testing in JUnit
  • Hamcrest Collections Matcher
  • Hamcrest equalTo () Matcher
  • AAA pattern of unit test (Arrange/Act/Assert)
  • Hamcrest Custom Matcher
  • Hamcrest Text Matcher
  • Why Junit uses Hamcrest
  • Java — ForkJoinPool
  • Java — How to use Futures
  • Java — Simple HashTable implementation
  • Java — Create a file in a specific path
  • Java — Mockito의 @Mock, @Spy, @Captor, @InjectMocks
  • Java — How to write test code using Mockito
  • Java — Synchronized block
  • Java — How to decompile a «.class» file into a Java file (jd-cli decompiler)
  • Java — How to generate a random number
  • Java — Calculate powers, Math.pow()
  • Java — Calculate the square root, Math.sqrt()
  • Java — How to compare String (==, equals, compare)
  • Java — Calculate String Length
  • Java — case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)

Источник

Читайте также:  Php редактировать pdf файл
Оцените статью