9

我正在尝试遵循 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.ScalaTestsrc/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.JavaTestsrc/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 上

4

1 回答 1

1

这类问题通常是由于类加载差异造成的,在这种情况下,差异并非微不足道。

在这个初始化阶段,LogManager静态初始化器在类第一次加载时被调用。如果您查看静态初始化程序内部,您将看到:

        Enumeration<URL> enumResources = null;
        try {
            enumResources = cl.getResources(LOGGER_RESOURCE);
        } catch (IOException e) {
            logger.fatal("Unable to locate " + LOGGER_RESOURCE, e);
        }

稍后在代码中,您将看到枚举资源的循环以创建记录器上下文工厂。

但是,当您运行 Scala 类enumResources.hasMoreElements()时返回true,而当您运行 java 类时它返回false(因此没有记录器上下文并且根本没有记录器被添加到 LogManager 中)。

如果您进一步调查,您会发现该cl变量实际上是一个类加载器,在 Java 类的情况下是一个实例,sun.misc.Launcher$AppClassLoader而对于 Scala 类是一个实例sbt.classpath.ClasspathUtilities$$anon$1

如果您查看静态初始化程序的开头,您将看到以下语句:

 static {
        // Shortcut binding to force a specific logging implementation.
        PropsUtil managerProps = new PropsUtil("log4j2.LogManager.properties");
        String factoryClass = managerProps.getStringProperty(FACTORY_PROPERTY_NAME);
        ClassLoader cl = findClassLoader(); 

所以你可能想看看这个findClassLoader()方法:

private static ClassLoader findClassLoader() {
            ClassLoader cl;
            if (System.getSecurityManager() == null) {
                cl = Thread.currentThread().getContextClassLoader();
            } else {
                cl = java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction<ClassLoader>() {
                        public ClassLoader run() {
                            return Thread.currentThread().getContextClassLoader();
                        }
                    }
                );
            }
            if (cl == null) {
                cl = LogManager.class.getClassLoader();
            }

            return cl;
        }

在这两种情况下,由于 SecurityManager 不为 null,它返回当前的 Thread 上下文类加载器。您的 Java 类和 Scala 类是不同的。

于 2012-12-28T09:27:23.290 回答