Friday, July 16, 2010

Logging three or more arguments in slf4j

I use slf4j for logging purposes. All the logging methods (, Logger.debug, etc.) provide an efficient way of passing one or two argument objects. For e.g."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:"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;
..."Status [{}], message [{}], time taken [{} ms].", toObjArr(status, msg, timeTaken));
A little-bit better readable than before.