Friday, July 16, 2010

Logging three or more arguments in slf4j

I use slf4j for logging purposes. All the logging methods (Logger.info, Logger.debug, etc.) provide an efficient way of passing one or two argument objects. For e.g.
logger.info("The response from server is [{}]", serverResp);
logger.debug("Key [{}], Value [{}].", key, value);
 But if you want to pass three or more arguments you have to create an object array yourself and pass. Like this:
logger.info("Status [{}], message [{}], time taken [{} ms].", new Object[]{status, msg, timeTaken});
Doing a new everywhere in the code doesn't seem like an elegant way of doing it. I was thinking about a cool way of doing it, and this is what I came up with. Here is a utility method that makes use of varargs:

public static Object[] toObjArr(Object... args) {
    return args;
}

In the code we can use this utility function like this.
import static com.mydomain.Utils.toObjArr;
...
    logger.info("Status [{}], message [{}], time taken [{} ms].", toObjArr(status, msg, timeTaken));
A little-bit better readable than before.

4 comments:

Anonymous said...

Thanks for the post, was was quite surprised that slf4j does not support varargs... But still better then the rest.

Barristan the Bold said...

Varargs were added in Java 1.5 right? So this was probably done to be backward compatible.

Anonymous said...

Thanka for the info. it helped. :)

ganesh said...

thanks