Exception in thread main java lang noclassdeffounderror org apache logging log4j logmanager

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger in Java [Solution]

Problem: You are getting Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger error in your Java application, which is using Log4j Logger either directly or indirectly via some popular Java framework like Spring, Struts or Hibernate.

Cause : Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger error indicates that JVM is not able to found org.apache.log4j.Logger class in your application’s CLASSPATH. The simplest reason for this error is the missing log4j.jar file. Since org.apache.log4j.Logger class belongs to this JAR file, if it’s not available at run-time then your program will fail.

Similar issue is java.lang.NoClassDefFoundError org.apache.log4j.Appender , which also comes due to missing log4j.jar in CLASSPATH. You can check that org.apache.log4j.Appender also belongs to log4j.jar file.

If you don’t know how then let me tell you a quick tip. If you have your project setup then you can simply type Ctrl + T and the name of the class e.g. org.apache.log4j.Logger and Eclipse will show all the class files with the same name along with the JAR file on which they are packaged. I often use this trick to find out whether a particular class is present in CLASSPATH or not.


Solution: If the problem is caused due to the missing log4j.jar file then you can fix it by adding a relevant version of log4j.jar into your CLASSPATH. Now, which version of the JAR file you should add will depend upon the application and library you are using but on the safer side, you can always add the latest one.

Читайте также:  Python язык программирования while

Btw, it’s worth remembering that there is a huge difference between Log4j and Log4j2, which also provides asynchronous logging, so make sure you add the right version of the log4j library into your application’s classpath.

You can download the log4j.jar file either from Maven central repository or directly from Apache Log4j website http://logging.apache.org/log4j/1.2/download.html. If you are using log4j 2 e.g. for asynchronous logging then you can download log4j2.jar from here. It exists on the same website but at a different location.

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

If you are using Maven then you can also add the following dependency in your pom.xml file to download Log4j.jar

dependency> groupId>log4j groupId> artifactId>log4j artifactId> version>1.2.15 version> dependency>
dependency> groupId>org.apache.logging.log4j groupId> artifactId>log4j-api artifactId> version>2.3 version> dependency>

That’s all about how to fix Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger error in Java application. In most cases, this issue will go away as soon as you add the log4j.jar file but if it still persists then you need to carefully check your CLASSPATH setting. You can see here to learn more about how to deal with CLASSPATH intricacies in Java.

  • How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory [solution]
  • How to solve java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject [solution]
  • Could not create the Java virtual machine Invalid maximum heap size: -Xmx [solution]
  • How to fix java.lang.unsupportedclassversionerror unsupported major.minor version 49.0 50.0 [fix]
  • How to deal with java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Java [solution]
  • How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledrive in JDBC [solution]
  • How to fix java.lang.NoClassDefFoundError: org/dom4j/DocumentException in Apache POI [fix]
  • How to solve java.lang.ClassNotFoundException: org.Springframework.Web.Context.ContextLoaderListener in Spring [solution]
  • Solution of java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver Error in JDBC [solution]
  • Solution of java.lang.ClassNotFoundException: org.postgresql.Driver error in Java? [solution]

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Could not initialize class org.apache.log4j.LogManager with Kafka #395

Could not initialize class org.apache.log4j.LogManager with Kafka #395

Comments

I’ve been trying to use the log4j appender with Kafka 0.10.1.1, but I am getting

Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class org.apache.log4j.LogManager at org.apache.log4j.Logger.getLogger(Logger.java:104) at kafka.utils.Logging$class.logger(Logging.scala:24) at kafka.Kafka$.logger$lzycompute(Kafka.scala:29) at kafka.Kafka$.logger(Kafka.scala:29) at kafka.utils.Logging$class.fatal(Logging.scala:115) at kafka.Kafka$.fatal(Kafka.scala:29) at kafka.Kafka$.main(Kafka.scala:72) at kafka.Kafka.main(Kafka.scala) 

without more information. I’ve added the following JARs to Kafka’s classpath:

slf4j-api-1.7.24.jar jackson-core-2.8.7.jar raven-8.0.2.jar raven-log4j-8.0.3.jar 

Output of running with -verbose (https://pastebin.com/kg1nqe9M) has

[Loaded org.apache.log4j.LogManager from file:/opt/kafka/libs/log4j-1.2.17.jar] 

Any idea? I am wondering if there could be a static initialisation issue somewhere whose exception would get swallowed, but not sure how to debug that.

The text was updated successfully, but these errors were encountered:

I downloaded Kafka 0.10.1.1 and put the following jars into the libs/ dir:

-rw-r--r--@ 1 brett staff 8.4K May 9 14:14 raven-log4j-8.0.3.jar -rw-r--r--@ 1 brett staff 134K May 9 14:14 raven-8.0.3.jar -rw-r--r--@ 1 brett staff 276K May 9 14:15 jackson-core-2.8.7.jar 

I then changed these lines in config/log4j.properties :

log4j.rootLogger=INFO, stdout, Sentry log4j.appender.Sentry=com.getsentry.raven.log4j.SentryAppender log4j.appender.Sentry.threshold=WARN 

Then I ran the Kafka broker:

SENTRY_DSN=»https://mydsn» ./bin/kafka-server-start.sh config/server.properties

Granted, I haven’t started ZK or anything on my local machine, so I immediately received a ton of errors. But those errors went to Sentry as expected:

Thanks for checking — the fact that it worked for you made me go over all non-standard things that I had in this environment, and I finally figured out the issue.

The above issue occurs because I had

export SENTRY_TAGS=component=kafka 

in my environment, which should be export SENTRY_TAGS=component:kafka , with a colon instead of = .

This is quite confusing that it would fail with a NoClassDefFoundError in this case, although I assume that raven does throw but that exception probably gets swallowed somehow.

Yeah, it looks like Sentry throws this (I’m not sure what Kafka is doing with it):

[WARNING] java.lang.ExceptionInInitializerError at org.apache.log4j.Logger.getLogger(Logger.java:104) at io.sentry.example.Application.(Application.java:7) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:293) at java.lang.Thread.run(Thread.java:745) Caused by: java.lang.IllegalArgumentException: Invalid tags entry: foo=bar at io.sentry.util.Util.parseTags(Util.java:46) at io.sentry.log4j.SentryAppender.setTags(SentryAppender.java:365) at io.sentry.log4j.SentryAppender.lazyInit(SentryAppender.java:153) at io.sentry.log4j.SentryAppender.activateOptions(SentryAppender.java:210) at org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:307) at org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:172) at org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:104) at org.apache.log4j.PropertyConfigurator.parseAppender(PropertyConfigurator.java:842) at org.apache.log4j.PropertyConfigurator.parseCategory(PropertyConfigurator.java:768) at org.apache.log4j.PropertyConfigurator.configureRootCategory(PropertyConfigurator.java:648) at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:514) at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:580) at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:526) at org.apache.log4j.LogManager.(LogManager.java:127) . 8 more 

Источник

log4j2 java.lang.NoClassDefFoundError: org/apache/logging/log4j/LogManager

Я использую log4j 2.3 в своем Java-приложении. Я добавил зависимость через maven.
При запуске программы в eclipse все работает нормально, но когда я упаковываю ее с помощью maven и пытаюсь запустить банку, я получаю следующую ошибку:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache logging/log4j/LogManager at main.myclass.(myclass.java:11) Caused by: java.lang.ClassNotFoundException: org.apache.logging.log4j.LogManager 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) . 1 more 

Почему он не может найти класс при запуске из банки? Добавление log4j 1.2 тоже не помогло. Программа работает нормально в eclipse, поэтому не должно быть отсутствующих зависимостей.

Вероятно, у вас произошел сбой зависимости, когда одна из ваших зависимостей имеет транзитивную зависимость от log4j 1.x. Используйте mvn dependency:tree , чтобы найти виновника. Также см. stackoverflow.com/questions/26338387/ — person Tobb &nbsp schedule 03.09.2015

Вам нужно иметь банку log4j в вашем пути к классу. Как вы выполняете свое приложение? — person Amila &nbsp schedule 03.09.2015

Есть ли способ сделать mvn dependency:tree в eclipse? Я не устанавливал maven для использования в командной строке, просто использую его в eclipse. Я добавил log4j-cire(2.3) и log4j-api(2.3) в качестве зависимостей в свой pom.xml. Я запускаю его из командной строки с помощью java -har myApplication.jar — person Pabi &nbsp schedule 03.09.2015

Ответы (2)

Когда вы запускаете банку приложения из командной строки, ваша зависимая банка недоступна во время выполнения. Вам нужно включить любой из этих двух плагинов в pom.xml, чтобы ваши зависимости были доступны во время выполнения. Использование: maven-shade-plugin

 org.apache.maven.plugins maven-shade-plugin 2.4.1  package shade    org.sonatype.haven.HavenCli       
 org.apache.maven.plugins maven-dependency-plugin 2.8  copy-dependencies package copy-dependencies  $/lib     

Когда вы выполните mvn package , он сгенерирует uber jar/или скопирует зависимости в outputDirectory. Я предпочитаю maven-shade-plugin для создания одной банки со всеми зависимостями.

Источник

Log4j2 java.lang.NoClassDefFoundError: org/apache/logging/log4j/LogManager

Я использую log4j 2.3 в своем приложении java. Я добавил зависимость через maven.
При запуске программы в eclipse все работает нормально, но когда я упаковываю его с помощью maven и пытаюсь запустить jar, я получаю следующую ошибку:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache logging/log4j/LogManager at main.myclass.(myclass.java:11) Caused by: java.lang.ClassNotFoundException: org.apache.logging.log4j.LogManager 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) . 1 more 

Почему он не может найти класс во время его запуска из банки?

Добавление log4j 1.2 тоже не сработало. Программа работает нормально в затмении, поэтому не должно быть недостающей зависимости.

Когда вы запускаете свою прикладную банку из командной строки, ваша зависимая банка недоступна во время выполнения. Вам нужно включить любой из этих двух плагинов в pom.xml, чтобы ваши зависимости были доступны во время выполнения.

 org.apache.maven.plugins maven-shade-plugin 2.4.1  package shade    org.sonatype.haven.HavenCli       
 org.apache.maven.plugins maven-dependency-plugin 2.8  copy-dependencies package copy-dependencies  $/lib     

Когда вы выполните mvn package , он будет генерировать uber jar/или скопировать зависимости в outputDirectory. Я предпочел бы, чтобы maven-shade-plugin генерировал одну jar, все зависимости.

Установите последнюю версию log4j (я установил log4j-2.3.jar ).

И выполните следующие шаги:

  • Щелкните правой кнопкой мыши проект → Путь сборки → Библиотеки → Добавить внешние файлы Jar → Включить файлы Log4j, Log4j core и Log4j api.

Источник

Оцените статью