Advertisement
Guest User

UncaughtExceptionLogger with OutOfMemory logging

a guest
Dec 16th, 2014
536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.26 KB | None | 0 0
  1. import java.util.Iterator;
  2. import java.util.Map;
  3.  
  4. import javax.annotation.PostConstruct;
  5.  
  6. import org.apache.commons.lang3.exception.ExceptionUtils;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9.  
  10. public class UncaughtExceptionLogger {
  11.  
  12.     private final static Logger logger = LoggerFactory.getLogger(UncaughtExceptionLogger.class);
  13.  
  14.     @PostConstruct
  15.     private void init() {
  16.         Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
  17.             public void uncaughtException(final Thread t, final Throwable e) {
  18.                 String msg = ExceptionUtils.getRootCauseMessage(e);
  19.                 logger.error(String.format("Uncaght exception handler captured expcetion '%s'", msg), e);
  20.                 if (msg.contains("unable to create new native thread")) {
  21.                     String dump = captureThreadDump();
  22.                     logger.error(String.format(
  23.                             "OutOfMemoryError has been captured for threads limit. Thread dump: \n %s", dump), e);
  24.                 }
  25.                 if (ExceptionUtils.getRootCause(e) instanceof OutOfMemoryError) {
  26.                     String dump = captureThreadDump();
  27.                     logger.error(String.format("OutOfMemoryError has been captured. Thread dump: \n %s", dump), e);
  28.                 }
  29.             }
  30.         });
  31.     }
  32.  
  33.     public static String captureThreadDump() {
  34.         /**
  35.          * http://stackoverflow.com/questions/2787976/how-to-generate-thread-
  36.          * dump-java-on-out-of-memory-error
  37.          * http://henryranch.net/software/capturing-a-thread-dump-in-java/
  38.          */
  39.         Map<Thread, StackTraceElement[]> allThreads = Thread.getAllStackTraces();
  40.         Iterator<Thread> iterator = allThreads.keySet().iterator();
  41.         StringBuffer stringBuffer = new StringBuffer();
  42.         while (iterator.hasNext()) {
  43.             Thread key = (Thread) iterator.next();
  44.             StackTraceElement[] trace = (StackTraceElement[]) allThreads.get(key);
  45.             stringBuffer.append(key + "\r\n");
  46.             for (int i = 0; i < trace.length; i++) {
  47.                 stringBuffer.append(" " + trace[i] + "\r\n");
  48.             }
  49.             stringBuffer.append("");
  50.         }
  51.         return stringBuffer.toString();
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement