8

SLF4J 的日志调用可变参数在我的 Java 工作中非常有用

Logger log = LoggerFactory.getLogger( getClass() );
log.debug( "Hello, {}.  The current time is {}", "robert", new Date() );

试图在 Play 2.1 Framework/Scala 中做这个简单的例子,我遇到了拒绝我的编译器。

import play.api._
import play.api.mvc._
import org.slf4j.LoggerFactory

object Application extends Controller {
  val log: org.slf4j.Logger = LoggerFactory.getLogger(getClass())

  def hb = Action {
    val message = makeMessage()
    // COMPILER HATES THIS:  ambiguous reference compiler error here
    log.info("Hello {}.  The current time is {}", "robert", new java.util.Date() )
    Ok(message)
  }
  def makeMessage(): String = { return "stuff" }
}

[dm2-server] $ compile
[info] Compiling 2 Scala sources to /Users/bobk/work/dm2-server/target/scala-2.10/classes...
[error] /Users/bobk/work/dm2-server/app/controllers/Application.scala:16: ambiguous reference to overloaded definition,
[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,java.util.Date)
[error]     log.info("Hello {}.  The current time is {}", "robert", new java.util.Date() )
[error]         ^
[error] one error found
[error] (compile:compile) Compilation failed
[error] Total time: 1 s, completed Jun 6, 2013 10:54:41 AM

那是什么错误,我该如何克服它来调用 SLF4J API?如果我不能这样做,我如何使用 Play 2.1 Logging Framework 在我的日志调用中获取可变参数?在 Scala 领域有些不对劲。

4

2 回答 2

6

您使用的是什么版本的 SLF4J?如果您可以回到 1.6.6 或更高版本,则可以避免此问题的歧义。不幸的是,这两个签名在 scala 中看起来完全一样,编译器似乎无法区分你的意思。常见的建议是回滚到不存在这种重载方法歧义的 SLF4J 版本(如果可能的话)。更多信息可以在以下链接中找到:

https://groups.google.com/forum/?fromgroups#!topic/scala-language/ms4IVIu-xGw

https://github.com/typesafehub/scalalogging/issues/16

于 2013-06-06T18:29:16.763 回答
1

对此的“快速修复”如下:

只需强制最后一个参数为 Any 类型即可解决编译器的问题(并减少代码...)

logger.debug("hello {} / {} ", "Hello", "World":Any)

或者在你的情况下:

log.info("Hello {}.  The current time is {}", "robert", new java.util.Date():Any)
于 2015-09-10T16:36:03.823 回答