Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala and SLF4J :: pass multiple parameters

Having the following code: log.info("parameters {} and {}", param1, param2) compiles and works well with SLF4J in Scala

However if I want to pass more arguments, I need to use Array:

log.info("parameters {} and {} and {}", Array(param1, param2,param3)) 

which simply substitutes first parameter with array.toString and leaves rest of parameters unbound.

The following code

log.info("parameters {} and {} and {}", Array(param1, param2,param3) : _*) 

doesn't compile, because of:

error: overloaded method value info with alternatives:
(org.slf4j.Marker,java.lang.String)Unit <and>
(java.lang.String,java.lang.Throwable)Unit <and>
(java.lang.String,Array[java.lang.Object])Unit <and>
(java.lang.String,Any)Unit
cannot be applied to (java.lang.String, Any)
log.info("parameters {} and {} and {}", Array(param1, param2,param3) : _*) 

What am I missing here?

like image 848
jdevelop Avatar asked Aug 13 '12 19:08

jdevelop


2 Answers

I guess it all depends on the inferred type. The log.info method that takes an array is expecting an Array[AnyRef]. So as an alternative to the cast you could do

log.info("parameters {} and {} and {}", Array[AnyRef](1, 2, "a"): _*)

But this won't work as there's a restriction on implicit conversions between Int -> AnyRef. For those, you'll need a type ascription:

log.info("parameters {} and {} and {}", 
   Array[AnyRef](1: Integer, 2: Integer, "a"): _*)

See this question for more details: Result type of an implicit conversion must be more specific than AnyRef

like image 107
Bruno Bieth Avatar answered Nov 05 '22 08:11

Bruno Bieth


You should use a scala wrapper for slf4j like grizzled

If you're not bound to slf4j, you should check out Logula. I've been playing with that recently and I like it.

like image 35
Falmarri Avatar answered Nov 05 '22 07:11

Falmarri