Adhoc logging in Eclipse

Background and motivation

Very often it is more useful to log variables to console or file (using Log4J for example) instead of using breakpoints and manually step over. Especially when the execution goes through the interesting line multiple times debugging can be quite annoying.

When we are dealing with our code, it is pretty easy to add a log statement to the specific part. When we are dealing with 3rd party code we don’t have such options. In such a case we can achieve this using AOP (e.g. AspectJ or Spring AOP), however sometimes it is just too heavy solution when we need to do this one time only to find a small bug or so.

One day I came accross an interesting article 5 Tips for Debugging Java Code in Eclipse written by Abdullah Cetin CAVDAR on September 13, 2008. Fredrik Attebrant made an interesting comment that helped me to achieve what I all the time wanted:

“Trace points” can to some extent be done by entering code into the “condition” of a conditional breakpoint.

First do some printing, then make sure to return false if you want the execution to continue.

Example:
System.out.println(” foo has size: ” foo.getSize());
return false;

How to use adhoc logging in Eclipse

So here we go… we will use conditional breakpoints in Eclipse to enable us to log important stuff.

Create a breakpoint on the line you are interested in. Right click that breakpoint and select Breakpoint Properties…. Check “Enable Condition” checkbox and input your code into the box below. The breakpoint icon will show a question mark on that line meaning that it is a conditional breakpoint now.

Code sample

The trick here is to do the output and then return false so that execution is not suspended and you do not have to interact with the debugger as it is exactly what we want to avoid (see the option below the text box: Suspend when – condition is true).

Conditional Breakpoint Properties

To test it, we obviously have to run the program using Debug instead of Run because we need to enable breakpoints. The output should be similar to following:

Started
LOG - 0
LOG - 1
LOG - 2
LOG - 3
LOG - 4
LOG - 5
LOG - 6
LOG - 7
LOG - 8
LOG - 9
Finished

There is more to try…

And going further we can even implement conditions (hence conditional breakpoint), so that we would log only under specific circumstances.