views:

138

answers:

3

Hi all:

I've got a method in my class only for testing purpose :

private void printOut(String msg, Object value)
{
    System.out.println(msg + value);
}

It is a wrapper method for System.out.println();

So I hope, with the use of Annotation, I can choose not to run this method during productive environment while still keep those diagnostic output ready if I am to switch back to debugging environment.

Which Annotation shall I put on top of the method name?

+5  A: 

One solution is to use AspectJ to do this, as you can control the behavior based on annotations.

Here is a tutorial on how to use annotations as join points:

http://www.eclipse.org/aspectj//doc/next/adk15notebook/annotations-pointcuts-and-advice.html

What you could do is to have:

@DebugMessage
private void printOut(String msg, Object value)
{ }

Then, in your aspect you could have the aspect do the println call.

This way, in production, the aspect isn't included, but, should you ever need to have this active, then just add the aspect, even to production code, to get some debugging.

James Black
Thanks for this tip, I will go there and see if I can implement this:)
Michael Mao
This definitely answers the original question, but I think using a logging framework is actually a better ultimate solution for the situation at hand.
Peter Recore
@Peter Recore - See my comment at the top, I agree with you, depending on the requirements of the OP.
James Black
+4  A: 

You should really follow uthark's advice and use a logging framework.

Those have been specifically designed for this situation.

Doing something "funky" will probably cause problems later on.

Thilo
+8  A: 

As I stated above you should use logging. Here are some of the benefits of using logging in an application:

  • Logging can generate detailed information about the operation of an application.
  • Once added to an application, logging requires no human intervention.
  • Application logs can be saved and studied at a later time.
  • If sufficiently detailed and properly formatted, application logs can provide audit trails.
  • By capturing errors that may not be reported to users, logging can help support staff with troubleshooting.
  • By capturing very detailed and programmer-specified messages, logging can help programmers with debugging.
  • Logging can be a debugging tool where debuggers are not available, which is often the case with multi-threaded or distributed applications.
  • Logging stays with the application and can be used anytime the application is run.

Read more about logging here

There are a lot of logging frameworks in java:

  1. Log4j
  2. java.util.logging
  3. Logback.

And several facades, which provides abstraction for various logging frameworks:

  1. slf4j
  2. commons-logging
uthark
This is just what I want. I should have made good use of those utilities rather than reinventing the wheel...
Michael Mao
+1 - For a simpler, and more effective answer. :)
James Black