Archive

Archive for the ‘Java’ Category

Make System.out.println() Rocks!

2012/10/18 15 comments

System.out.println() is very strong and useful debug tool for long time.
The problem is that we tend to don’t remove this code after we debug.

What if do we have a lots of codes which we forgot to remove, finally debug messages can be useless trashes.
But tracing location of println() code is very difficult since we can’t use break points on system console stream.

So, Here is a cool solution:

@Override
/**
 * @author Jeeeyul 2011. 11. 1. 오후 4:36:51
 * @since M1.10
 */
public class DebugStream extends PrintStream {
   private static final DebugStream INSTANCE = new DebugStream();

   public static void activate() {
      System.setOut(INSTANCE);
   }

   private DebugStream() {
      super(System.out);
   }

   @Override
   public void println(Object x) {
      showLocation();
      super.println(x);
   }

   @Override
   public void println(String x) {
      showLocation();
      super.println(x);
   }

   private void showLocation() {
      StackTraceElement element = Thread.currentThread().getStackTrace()[3];
      super.print(MessageFormat.format("({0}:{1, number,#}) : ", element.getFileName(), element.getLineNumber()));
   }
}

Just call DebugStream.activate() when your application start.

It converts messages in console view from:

Hello World.

into:

(MyHelloWorld.java:10) : Hello World.

Yes, you can click and jump to your System.out.println() code in Eclipse console view. It makes debugging so easy.

Advertisements
Categories: Eclipse, Java