When you do something like LOG.debug("Exported {}.", product) in slf4j it will eventually call toString() on the arguments, e.g. product.
For certain reasons, I can’t override toString() on all the classes I want to use as arguments. Some classes come from third party jars, others will have their toString() called in other contexts, too, where the information I want to print in my log statement isn’t available.
However, I have a class for debugging purposes which has a method DebugFormatter.format(Object) that has a long cascade of instanceofs that selects the routine to find some useful debugging information about that object.
My question is: Is it possible to configure slf4j so that it calls such a static method instead of toString()?
Of course, I could call my format method on the object before passing it as a parameter to Logger.debug() but then it would be executed even when the respective logger is not enabled. So I had to surround it with if (LOG.isDebugEnabled()) which means that the whole point of having arguments in debug() was missed.
You could create a shim, taking your object and calling
DebugFormatter.format()from itstoString()function. Something like this:With the appropriate static import, your logging statement becomes this:
This does have slightly more overhead than passing the object in straight, but it’s a small, constant overhead — and the object created will be very short-lived.