java print complete stack information

foreword

In actual projects, it is inevitable to encounter various exceptions. Usually we have a log system to collect error information and stack information, such as graylog, flume+kafka+storm, elk, etc.
But when encountering an exception, we also need to notify us of the abnormal situation by email, WeChat or SMS. Since WeChat and SMS have restrictions on the length of the text, we will print out the specific stack information and notify us by email.

  1. Use the io stream to print out the stack information
 public static String getStackTrace(Exception e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();

        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }
  1. Use the tool classes provided by common-lang3

The ExceptionUtils class is provided in the common-lang3 package to help read stack information

pom dependencies:

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.5</version>
</dependency>
public static String getStackTraceV2(Exception e) {
    return org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
}

Take a look at how the source code is implemented:

//-----------------------------------------------------------------------
 /**
  * <p>Gets the stack trace from a Throwable as a String.</p>
  *
  * <p>The result of this method vary by JDK version as this method
  * uses {@link Throwable#printStackTrace(java.io.PrintWriter)}.
  * On JDK1.3 and earlier, the cause exception will not be shown
  * unless the specified throwable alters printStackTrace.</p>
  *
  * @param throwable  the <code>Throwable</code> to be examined
  * @return the stack trace as generated by the exception's
  *  <code>printStackTrace(PrintWriter)</code> method
  */
 public static String getStackTrace(final Throwable throwable) {
     final StringWriter sw = new StringWriter();
     final PrintWriter pw = new PrintWriter(sw, true);
     throwable.printStackTrace(pw);
     return sw.getBuffer().toString();
 }

It is the same as the first method, so there are many things that others have already built wheels, and we can use them directly, but we also need to understand the principles of their implementation.

Guess you like

Origin blog.csdn.net/wjavadog/article/details/93778802