Logging/bugtracing using Spring 2, AOP, Reflection and Log4J
One of the most cumbersome tasks to perform when developing applications is implementing logging/bugtracing functionality. It’s a lot of work, error-prone and plain boring. Unfortunately, it’s an essential piece of any application because it is one of the best (and often only) means to trace problems in a production environment. Lucky for us, this task can be made quite easy using a combination of Spring 2, AOP, Reflection and Log4J.
Requirements
Assume the following case: we want to log each method-call to one of our services together with the input parameters and their attributes, as well as the return value and its attributes.
Design
The solution will consist of three components:
- A MethodInterceptor implementation which will intercept method calls to our services and log all required information using Log4J;
- A utility class which will create a meaningful toString() representation of a given object using theReflection API;
- A piece of Spring configuration to wire the Interceptor in our application using an AutoProxyCreator.
I will provide a detailed description of each below, as well as the source code. I’m still struggling with the layout here, so I will provide the actual files as well.
LoggingInterceptor
The LoggingInterceptor will check if the log is debug-enabled. If it is not it will simply delegate the method call. If debug is enabled it will log the name of the service, the name of the method and any input parameters (including their properties!) using the LoggingUtil utility class. Then it will proceed with the MethodInvocation. After returning it will log the return value (if present), again including it’s properties.
LoggingUtil
Creating a toString() method on each object is (again) a lot of work, cumbersome and just plain boring. Wouldn’t it be nice if we had a generic way to create a String representation of a JavaBean which we only have to write once? This utility class will do just that. It will create a String representation of a JavaBean by getting its classname and then calling every no-argument getter method (as specified by the JavaBeans standard for property getter methods) using the Reflection API. The result of each call is appended to the result String. No need to implement a toString() method on every object anymore!
applicationcontext.xml
Using Spring’s excellent BeanNameAutoProxyCreator we’ll wire the LoggingInterceptor to every bean which name is ending with ‘Service’. This will ensure that logging is applied to all our service calls.
Well, that’s it! I hope this article was useful to you. If it was or wasn’t, please let me know by placing a comment.
Cheers
Lars Rosenquist



(4 votes, average: 3.75 out of 5)