Scala and SLF4J :: pass multiple parameters

自作多情 提交于 2020-01-03 08:48:13

问题


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?


回答1:


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




回答2:


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.




回答3:


what if you use string interpolation? like so:

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



回答4:


Try this:

Array(...).asInstanceOf[Array[Object]]



回答5:


Here is how I do it.

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

Cheers



来源:https://stackoverflow.com/questions/11940614/scala-and-slf4j-pass-multiple-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!