package com.yammer.metrics.util;

import com.yammer.metrics.core.Counter;

/**
 * When a thread throws an Exception that was not caught, a DeathRattleExceptionHandler will
 * increment a counter signalling a thread has died and print out the name and stack trace of the
 * thread.
 * <p/>
 * This makes it easy to build alerts on unexpected Thread deaths and fine grained used quickens
 * debugging in production.
 * <p/>
 * You can also set a DeathRattleExceptionHandler as the default exception handler on all threads,
 * allowing you to get information on Threads you do not have direct control over.
 * <p/>
 * Usage is straightforward:
 * <p/>
 * <pre><code>
 * final Counter c = Metrics.newCounter(MyRunnable.class, "thread-deaths");
 * Thread.UncaughtExceptionHandler exHandler = new DeathRattleExceptionHandler(c);
 * final Thread myThread = new Thread(myRunnable, "MyRunnable");
 * myThread.setUncaughtExceptionHandler(exHandler);
 * </code></pre>
 * <p/>
 * Setting the global default exception handler should be done first, like so:
 * <p/>
 * <pre><code>
 * final Counter c = Metrics.newCounter(MyMainClass.class, "unhandled-thread-deaths")
 * Thread.UncaughtExceptionHandler ohNoIDidntKnowAboutThis = new DeathRattleExceptionHandler(c)
 * Thread.setDefaultUncaughtExceptionHandler(ohNoIDidntKnowAboutThis)
 * </code></pre>
 */
public class DeathRattleExceptionHandler implements Thread.UncaughtExceptionHandler {
    final private Counter deathRattle;

    public DeathRattleExceptionHandler(Counter deathRattle) {
        this.deathRattle = deathRattle;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        deathRattle.inc();
        System.err.println("Uncaught exception on thread " + t);
        e.printStackTrace();
    }
}

@@ -66,16 +66,73 @@
 Counter;
+%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;
 %0A%0A/**%0A *
@@ -1202,16 +1202,17 @@
 deaths%22)
+;
 %0A * Thre
@@ -1299,16 +1299,17 @@
 ndler(c)
+;
 %0A * Thre
@@ -1370,16 +1370,17 @@
 outThis)
+;
 %0A * %3C/co
@@ -1483,21 +1483,117 @@
 r %7B%0A    
-final
+private static final Logger LOGGER = LoggerFactory.getLogger(DeathRattleExceptionHandler.class);%0A%0A   
  private
@@ -1593,16 +1593,22 @@
 private 
+final 
 Counter 
@@ -1842,26 +1842,20 @@
     
-System.err.println
+LOGGER.error
 (%22Un
@@ -1890,37 +1890,11 @@
  + t
-);%0A        e.printStackTrace(
+, e
 );%0A 

Switch DeathRattleExceptionHandler over to slf4j.