我已将此分离为一个非常简单的测试项目,除了简单的log4j2test配置+用法之外没有任何其他目的。文件目录结构:
.
├── build.sbt
└── src
└── main
├── resources
│ └── log4j2.xml
└── scala
└── mycompany
└── myapp
└── SimpleMain.scala
Build.sbt:
name := """log4j2test"""
version := "1.0.0-SNAPSHOT"
scalaVersion := "2.12.1"
scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")
libraryDependencies ++= {
Seq(
"org.apache.logging.log4j" % "log4j-slf4j-impl" % "2.8",
"org.apache.logging.log4j" % "log4j-api" % "2.8",
"org.apache.logging.log4j" % "log4j-core" % "2.8",
"com.fasterxml.jackson.dataformat" % "jackson-dataformat-yaml" % "2.8.6"
)
}
log4j2.xml内容是从官方文档中的示例中复制/粘贴的:https://logging.apache.org/log4j/2.x/manual/configuration.html
SimpleMain.scala:
package mycompany.myapp
import org.slf4j.LoggerFactory
object SimpleMain {
val logger = LoggerFactory.getLogger(getClass())
def main(args: Array[String]): Unit = {
println("simple println test")
logger.info("this is a logger.info message")
logger.debug("this is a logger.debug message")
logger.error("this is a logger.error message")
val stream = this.getClass.getClassLoader.getResourceAsStream("log4j2.xml")
if (stream == null) {
println("failed to open log4j2.xml on classpath")
} else {
println("successfully opened log4j2.xml on classpath")
stream.close()
}
}
}
我用
运行sbt "run-main mycompany.myapp.SimpleMain"
输出:
[info] Running mycompany.myapp.SimpleMain
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
simple println test
14:12:14.508 [run-main-0] ERROR mycompany.myapp.SimpleMain$ - this is a logger.error message
successfully opened log4j2.xml on classpath
[success] Total time: 4 s, completed Feb 10, 2017 2:12:14 PM
答案 0 :(得分:0)
SimpleMain应用程序的类加载器是否可能与slf4j的类加载器不同?请尝试通过将系统属性org.apache.logging.log4j.simplelog.StatusLogger.level
设置为TRACE
来调试Log4j2初始化。
答案 1 :(得分:0)
log4j2.xml是否放在jar的根目录下?我很惊讶getResourceAsStream正在工作。您将它指定为相对路径,因此应该找到/mycompany/myapp/log4j2.xml。