Skip to main content

AspectJ: Please don't use System.out.println

Posted by ahashim on July 24, 2008 at 1:39 PM PDT

Usually if you are working in a "big" project and doing a code review; if you have a vendor who develop some application for your company; if you have a fresh graduate developer ... you will find a lot of bad-practices in the code being written! I don't like to see System.out.println() in the code .. because simply, it doesn't appears in the log files!!!

As a solution, you can use Aspects to figure out the pointcuts in the code which uses "SYSO" and the advice will be to log the message yourself.

Let's have a look into the code and how this will work:-

1- the idiot code will be like that

aop1.PNG

as you see, the method add() will print some info the default output stream which is the console. This method is called from the main method. If you are an eclipse user, you will notice that there is a small orange arrow on the left side of the code editor referring to the line of code uses "SYSO"; we will back to this arrow after while ;).

2- We will now create a new aspect to solve this problem, the BPAspect will looks like the following:-

aop3.PNG

to define a pointcut to SYSO, the pointcut definition will be

pointcut syso():call(* java.io.PrintStream.print*(..));

which means: define a pointcut named syso and get all places which call a method print,println as a members in the PrintStream class, take any argument and return any value.

then, mark the called for this method as warning in your code and display this message "Don't use SYSO"

declare warning:syso():"Don't use SYSO";

then, how to log the message? the advice will come to do this job

after():syso(){logger.info(thisJoinPoint.getArgs()[0]);}

3- What about the orange arrow? it indicates that there is an pointcut which this line matches with.

There is a panel also shows the aspects which reference the code in this class

aop2.PNG

on the other side, if you open the aspect code, the panel will show the code referenced by the aspects.

aop4.PNG

you will see also that there is a warning message in this line

aop5.PNG

4- Now, we can run the application to see how it will work
It will print the to the console

Add 1 to 2
2008-07-24 14:28:22,828 [main] INFO BPAspect - Add 1 to 2

and prints to the log file
2008-07-24 14:28:22,828 [main] INFO BPAspect - Add 1 to 2

Related Topics >>