Tuesday, April 7, 2009

AspectJ for Java Logging: Individual tracing control per Java package - Part 5

In "AspectJ for Java logging: Serviceability without the clutter - part 2" I had some difficulty in assigning a different trace handler for each class, which severely limited the application of the "Logging" aspect on larger programs. After all, it does not make sense to enable verbose trace on method entry/exit for all modules when debugging a single module.

A few minutes ago, some more reading solved the problem: one can use the "pertypewithin" aspect declaration, like this:

public aspect Logging pertypewithin(my.project..* && !Exception+){

/**
* Trace handler for each type.
*/
private static Logger trace = null;

/**
* Initialization of all classes in the project.
*/
pointcut projectClassInitializer() :
staticinitialization(my.project..*) &&
!within(Logging);

/**
* After the initialization of all classes in this project.
*/
after(): projectClassInitializer() {
String classname = thisJoinPointStaticPart.getSourceLocation().getWithinType().getName();
trace = Logger.getLogger("trace." + classname);
}

...

}


Now, the pointcut "projectClassInitializer" will pick out the static declaration of all Java classes within the project. Exceptions declared in the project are left out, as I do not see usefulness in instrumenting such basic classes, but that is a matter of preference.



The "after" advice will guarantee that the "trace" handler is initialized at the end of the static initialization for each class, using a handle named "trace.<classname>".



With this arrangement, it is now possible to configure different tracing levels within the logging.properties file for your java application, setting a different level for an entire package or for a single class, like this:




handlers = java.util.logging.ConsoleHandler
#handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler

trace.my.level = INFO
trace.com.ibm.project.module1.level = INFO
trace.com.ibm.project.module2.level = FINEST
trace.com.ibm.project.module2.ClassA.level = FINER
...



-----

No comments:

Post a Comment