Posts

Showing posts with the label SLF4J

A minor annoyance with two argument logging in SLF4J and Scala

I am using Scala for one of my recent projects. For logging, I am using SLF4J/LOGback. There is one minor annoyance while you are trying to log two argument messages like: logger.info("Some log with arg1 [{}] and arg2 [{}].", arg1, arg2) While you compile with sbt you will get the following error: [error] both method info in trait Logger of type (x$1: String, x$2: <repeated...>[Object])Unit [error] and  method info in trait Logger of type (x$1: String, x$2: Any, x$3: Any)Unit [error] match argument types (String,String,String)   If you are getting this error, a small trick that I did to avoid casting to AnyRef or Object was to just add a null argument at the end which will force the Scala compiler to make use of the vararg version. LOGBack just ignores extraneous arguments. Like this: logger.info("Some log with arg1 [{}] and arg2 [{}].", arg1, arg2, null) Disclaimer: I am a Scala rookie, hence take my advice with a pinch of salt!  

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].", toOb...