Is there a Java library that adds annotations for Logging?
http://aspect4log.sf.net allows you to log method calls, arguments, returned value, thrown exception (it even allows you to change the log level depending on exception, by default it uses ERROR for unchecked exceptions and WARN for checked exceptions. It helped me a lot in removing boilerplate code and improved logging.
I've also know about http://loggifier.unkrig.de - it does logging via java.util.logging (which no one uses), a bit too complex to setup and not that well document but it has one BIG feature - it claims that it can instrument already compiled jar/war/ear files (which is great if u want to profile someone's uglry jar which u can not recompile)!
Bottom line - if u own the code, aspect4log is your choice. If you do not own the code - go for loggifier.
I have created a project called log-weaver, which introduces a number of @LogXXX statements.
When you compile a project, that uses one of these annotations, Log-statements are weaves into the bytecocde.
Example source code:
@LogEnteringAndExiting(value={"arg1", "this"})
public String execute(String arg1) {
/*Some logic*/
return "done";
}
The source code will remain as is, but the byte code will look as if the source code had been written like this:
private static final Logger comGithubHervian_LOGGER = LoggingHelper.getLogger(ClassWithLogAnnotatedMethods.LogAround_log1ArgumentAndThis.class);
private static final String = comGithubHervian_CLASSNAME = ClassWithLogAnnotatedMethods.LogAround_log1ArgumentAndThis.class.getName();
public String execute(String arg1) {
if (LoggingHelper.isEntryExitTraceEnabled((Logger)comGithubHervian_LOGGER)) {
comGithubHervian_LOGGER.entering(comGithubHervian_CLASSNAME, "execute", new Object[]{arg1, this});
}
/*Some logic*/
String string = "done";
if (LoggingHelper.isEntryExitTraceEnabled((Logger)comGithubHervian_LOGGER)) {
comGithubHervian_LOGGER.exiting(comGithubHervian_CLASSNAME, "execute", string);
}
return string;
}
In the code above the LoggingHelper is a special class from IBM's WebpShere Commerce for which this proof of concept was developed.
The idea is to simplify the source code by removing trivial statements, in this case logging.
The overall logic is as follows:
- An AbstractProcessor detects the usage of one the log annotations, and creates some useful data structure, to hold information about the method name, arguments etc.
- The AbstractProcessor registers a TaskListener at the compiler (Javac).
- The TaskListener uses Javassist to weave log statements into the byte code of the given method/class.
Please be aware that the current project is designed for use with IBM's WebSphere Commerce, but you could easily adjust it, such as to weave log-statements of your own choosing into the code.