我正在尝试遵循 SBT 0.12.1 项目中的log4j2 配置教程。这是我的build.sbt:
name := "Logging Test"
version := "0.0"
scalaVersion := "2.9.2"
libraryDependencies ++= Seq(
"org.apache.logging.log4j" % "log4j-api" % "2.0-beta3",
"org.apache.logging.log4j" % "log4j-core" % "2.0-beta3"
)
我有两个独立的主要课程。第一个logtest.ScalaTest
在src/main/scala/logtest/ScalaTest.scala:
package logtest
import org.apache.logging.log4j.{Logger, LogManager}
object ScalaTest {
private val logger = LogManager.getLogger(getClass())
def main(args: Array[String]) {
logger.trace("Entering application.")
val bar = new Bar()
if (!bar.doIt())
logger.error("Didn't do it.")
logger.trace("Exiting application.")
}
}
第二个logtest.JavaTest
在src/main/java/logtest/JavaTest.java:
package logtest;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
public class JavaTest {
private static Logger logger = LogManager.getLogger(JavaTest.class.getName());
public static void main(String[] args) {
logger.trace("Entering application.");
Bar bar = new Bar();
if (!bar.doIt())
logger.error("Didn't do it.");
logger.trace("Exiting application.");
}
}
如果我logtest.ScalaTest.main()
从 sbt 内部运行,我会得到我期望的输出,因为src/main/resources/log4j2.xml将根日志记录级别设置为跟踪:
> run-main logtest.ScalaTest
[info] Running logtest.ScalaTest
10:26:23.730 [run-main] TRACE logtest.ScalaTest$ - Entering application.
10:26:23.733 [run-main] TRACE logtest.Bar - entry
10:26:23.733 [run-main] ERROR logtest.Bar - Did it again!
10:26:23.733 [run-main] TRACE logtest.Bar - exit with (false)
10:26:23.733 [run-main] ERROR logtest.ScalaTest$ - Didn't do it.
10:26:23.733 [run-main] TRACE logtest.ScalaTest$ - Exiting application.
[success] Total time: 0 s, completed Dec 21, 2012 10:26:23 AM
但是,当我 logtest.JavaTest.main()
从 sbt 内部运行时,我得到不同的输出
> run-main logtest.JavaTest
[info] Running logtest.JavaTest
ERROR StatusLogger Unable to locate a logging implementation, using SimpleLogger
ERROR Bar Did it again!
ERROR JavaTest Didn't do it.
[success] Total time: 0 s, completed Dec 21, 2012 10:27:29 AM
据我所知,ERROR StatusLogger Unable to ...
这通常表明 log4j-core 不在我的类路径中。缺少 TRACE 消息似乎表明我的 log4j2.xml 设置也不在类路径上。如果我运行 Foo.main 与 LoggerTest.main,为什么类路径会有任何差异?还是有其他原因导致这种行为?
更新
我使用 SBT Assembly 构建了这个项目的胖 jar,并指定 logtest.JavaTest 为主类。从命令行运行它会产生正确的结果:
$ java -jar "Logging Test-assembly-0.0.jar"
10:29:41.089 [main] TRACE logtest.JavaTest - Entering application.
10:29:41.091 [main] TRACE logtest.Bar - entry
10:29:41.091 [main] ERROR logtest.Bar - Did it again!
10:29:41.091 [main] TRACE logtest.Bar - exit with (false)
10:29:41.091 [main] ERROR logtest.JavaTest - Didn't do it.
10:29:41.091 [main] TRACE logtest.JavaTest - Exiting application.
GitHub 示例
按照 Edmondo1984 的建议,我整理了一个完整的例子,放到了github 上。