Search code examples
javagradlelogginglog4jbuild.gradle

NoClassDefFoundError when using Log4J


I wrote a small script to try Log4J, but always an error occurs:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/logging/log4j/LogManager
        at de.redstonepfalz.cachebuilder.CacheBuilder.<clinit>(CacheBuilder.java:7)
Caused by: java.lang.ClassNotFoundException: org.apache.logging.log4j.LogManager
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        ... 1 more

In the build.gradle file I have entered log4j-core and log4j-api in the latest version and the libraries are also installed. IntelliJ does not show me any error. Also when compiling no error message appears.

Does anyone know what I did wrong?

Here is the Java-Code:

package de.redstonepfalz.cachebuilder;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

public class CacheBuilder {
    private static final Logger logger = LogManager.getLogger(CacheBuilder.class);

    public static void main(String[] args) {
        logger.trace("Skript wird gestartet");
        logger.error("Ein Fehler ist aufgetreten");
        logger.fatal("Fatal");
        logger.info("Ein Infofall ist aufgetreten");
        logger.warn("Ein Warnung ist aufgetreten");
        logger.debug("Debug messsage");
        logger.trace("Skript wird beendet");
        System.out.println("Hello world!");
    }
}

build.gradle: https://pastebin.com/JftEB0QD


Solution

  • I've found the error. The Log4J-Library wasn't included in the single jar-file. I've installed and configured the Gradle plugin ShadowJAR and now, it works!