DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

I am an entrepreneur which currently bootstrapping my 2nd start-up. Uri has posted 4 posts at DZone. You can read more from them at their website. View Full User Profile

Converting a StackTrace to a String in Java

02.19.2014
| 2723 views |
  • submit to reddit


    

Converting a StackTrace to a String is a very popular question mostly asked by new developers while diving into the Java world.

Since there's more than one way to skin a cat, here are few ways this can be achieved.

  1. Writing the code yourself: 

    public static String convertStackTrace(Throwable t){
    	StringWriter sw = new StringWriter();
    	PrintWriter pw = new PrintWriter(sw);
    	t.printStackTrace(pw);		
    	return sw.toString();		
    }

  2. Using an open source, such as Apache Commons Lang

    Apache Commons Lang 

    import org.apache.commons.lang.exception.ExceptionUtils;
    
    public class CommonsTest{    
    
      public static void main(String[] args){
    		 try{
    			 ...
    		}catch(Exception ex){
    			ExceptionUtils.getStackTrace(exception) 
    		}     
      }
    }


  3.  Using a Logging system (open source), such as Log4J.
     In this case Log4J will convert the String from the StackTrace.

    Log4J

    import org.apache.log4j.Logger;
    
    public class Log4JTest{
      
      static Logger log = Logger.getLogger(Log4JTest.class.getName());
    
      public static void main(String[] args){
    		 try{
    			 ...
    		}catch(Exception ex){
    			log.error("Error ",ex);     
    		}     
      }
    }

  4. Using Java built in logger infrastructures:
     In this case Java logger will convert the String from the StackTrace.

    import java.util.logging.Logger;
    import java.util.logging.Level;
    
    public class LogTest{
      
      private final static Logger log = Logger.getLogger(LogTest.class.getName()); 
    
      public static void main(String[] args){
    		 try{
    			 ...
    		}catch(Exception ex){
    			log.log(Level.SEVERE, "Error ",ex);     
    		}     
      }
    }