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 replaces the first parameter with array.toString and leaves the rest of the parameters unconnected.

Following code

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

not compiled due to:

 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?

+6
source share
5 answers

You should use a scala wrapper for slf4j like grizzled

If you are not attached to slf4j, you should check Logula . I recently played with this and I like it.

+2
source

I think it all depends on the intended type. The log.info method, which takes an array, expects an array [AnyRef]. So, as an alternative to the throw, you could do

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

But this will not work, since there is a restriction on implicit conversions between Int → AnyRef. For them you will need a caption such as:

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

See this question for more information: Implicit conversion result type should be more specific than AnyRef

+2
source

What if you use string interpolation? So:

 log.info(f"parameters ${param1} and ${param2} and ${param3}") 
0
source

Try the following:

 Array(...).asInstanceOf[Array[Object]] 
-1
source

This is how I do it.

LOGGER.info ("encode: {}, code: {}, length: {}", Array (messageWrapper, methodCode, bytes.length) .asInstanceOf [Array [AnyRef]])

Greetings

-1
source

Source: https://habr.com/ru/post/922765/


All Articles