【问题标题】:"No log4j2 configuration file found."“找不到 log4j2 配置文件。”
【发布时间】:2025-12-05 12:05:01
【问题描述】:

我已将其隔离为一个非常简单的测试项目,除了简单的 log4j2test 配置 + 使用之外没有其他目的。文件目录结构:

.
├── build.sbt
└── src
└── main
    ├── resources
    │   └── log4j2.xml
    └── scala
    └── mycompany
        └── myapp
        └── SimpleMain.scala

构建.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

【问题讨论】:

  • 在初始化 SBT 时尝试将log4j.configurationFile=path/to/log4j2.xml 添加到您的类路径中。
  • 我不需要这样做。我应该只在类路径上有文件。
  • 我的同事选择使用log4j2,两年来人机工程学一直很差。 -D 的配置感觉就像 1999 年。
  • @som-snytt 我创建了issues.apache.org/jira/browse/LOG4J2-1811 来改进 Log4j2 的人体工程学。请添加您的反馈和想法。

标签: scala log4j2


【解决方案1】:

SimpleMain 应用程序的类加载器是否可能与 slf4j 的类加载器不同?请尝试通过将系统属性org.apache.logging.log4j.simplelog.StatusLogger.level 设置为TRAC‌​E 来调试Log4j2 初始化。

【讨论】:

    【解决方案2】:

    log4j2.xml 是否被放置在 jar 的根目录中?我很惊讶 getResourceAsStream 正在工作。您已将其指定为相对路径,因此它应该找到 /mycompany/myapp/log4j2.xml。

    【讨论】: