I am trying to use log4j to print logs to a log file. It works perfectly. But when I export the project as a jar file and run it I get an error
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/Logger
at com.mkyong.HelloExample.<clinit>(HelloExample.java:7)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Logger
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
The project structure is as follows https://www.mkyong.com/logging/log4j-hello-world-example/
Could someone please help?
Of corse. Your problem is that you need to include the log4j.jar
library when executing. You may do it in either of two ways:
Manually: If you run the jar within Eclipse, it is enough to execute Run As > Run Configurations... > classpath > Add JARS (or external JARs) and select the log4j.jar
.
Automatically: Include into the META-INF/MANIFEST.MF
file a classpath declaration:
Class-Path: log4j.jar
(See the Oracle documentation ).
This way has the advantage that you won't have to include libraries at execution time, even when executing out of Eclipse. But remember to distribute the log4.jar
along with your own jar.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.