Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SBT run differences between scala and java?

I'm trying to follow the log4j2 configuration tutorials in a SBT 0.12.1 project. Here is my 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"
)

I have two separate main classes. The first is logtest.ScalaTest in 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.")
  }
}

and the second is logtest.JavaTest in 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.");
  }
}

If I run logtest.ScalaTest.main() from inside sbt I get the output I was expecting given that src/main/resources/log4j2.xml sets the root logging level to trace:

> 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

However, when I run logtest.JavaTest.main() from inside sbt I get different output

> 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

From what I can tell, ERROR StatusLogger Unable to ... is usually a sign that log4j-core is not on my classpath. The lack of TRACE messages seems to indicate that my log4j2.xml settings aren't on the classpath either. Why should there be any difference in classpath if I'm running Foo.main versus LoggerTest.main? Or is there something else causing this behavior?

Update

I used SBT Assembly to build a fat jar of this project and specified logtest.JavaTest to be the main class. Running it from the command line produced correct results:

$ 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 Example

Following Edmondo1984's suggestion, I put together a complete example and put it up on github.

like image 644
Quigibo Avatar asked Dec 19 '12 15:12

Quigibo


People also ask

Can you use sbt for Java?

sbt is built for Scala and Java projects.

Which Java is sbt using?

sbt is a build tool for Scala, Java, and more. It requires Java 1.8 or later.

Does sbt run tests in parallel?

sbt maps each test class to a task. sbt runs tasks in parallel and within the same JVM by default.

What is sbt based Scala project?

sbt is a popular tool for compiling, running, and testing Scala projects of any size. Using a build tool such as sbt (or Maven/Gradle) becomes essential once you create projects with dependencies or more than one code file.


1 Answers

These kind of issues are very often due to class-loading difference and in this case the difference is non trivial.

During this initialization phase, the LogManager static initializer is called when the class is firstly loaded. If you look inside the static initializer you will see:

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

Later in the code, you will see a loop over the enum resources to create the logger context factory.

However, when you run the Scala class enumResources.hasMoreElements() returns true, while when you run the java class it returns false (so no logger context and no loggers are added at all to the LogManager).

If you investigate further, you will see that the cl variable is in fact a class loader, which in case of the Java class is an instance of sun.misc.Launcher$AppClassLoader while for the Scala class is an instance sbt.classpath.ClasspathUtilities$$anon$1

If you look at the beginning of the static initializer, you will see that the following statement:

 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(); 

So you might want to have a look to the findClassLoader() method:

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;
        }

In both case, since the SecurityManager is not null, it returns the current Thread context class loader. Which is different for your Java class and your Scala class.

like image 105
Edmondo1984 Avatar answered Sep 19 '22 14:09

Edmondo1984