开发者

Use Java Annotation not to run a method

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

private void prin开发者_如何学运维tOut(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?


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜