- SLF4J – Сообщения об ошибках
- Не удалось загрузить класс “org.slf4j.impl.StaticLoggerBinder”.
- Поставщики SLF4J не найдены
- Classpath содержит привязки SLF4J для версий slf4j-api до 1.8
- NoClassDefFoundError: org / apache / commons / logging / LogFactory
- Обнаружил как jcl-over-slf4j.jar, так и связанный slf4j-jcl.jar на пути к классам.
- Обнаружено несоответствие имени регистратора
- Classpath содержит несколько привязок SLF4J.
- Обнаружены оба log4j-over-slf4j.jar И привязанные slf4j-log4j12.jar на пути к классам
- How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
- 1 comment:
SLF4J – Сообщения об ошибках
В этой главе мы обсудим различные сообщения об ошибках или предупреждения, которые мы получаем при работе с SLF4J, и причины / значения этих сообщений.
Не удалось загрузить класс “org.slf4j.impl.StaticLoggerBinder”.
Это предупреждение, которое вызывается, если в пути к классам нет привязок SLF4J.
Ниже приводится полное предупреждение –
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Чтобы решить эту проблему, необходимо добавить одну из привязок каркаса ведения журнала. Это объясняется в главе Hello World этого урока.
Примечание. Это происходит в версиях SLF4J между 1.6.0 и 1.8.0-бета2.
Поставщики SLF4J не найдены
В slf4j-1.8.0-beta2 вышеупомянутое предупреждение более ясно говорит, что «поставщики SLF4J не были найдены» .
Ниже приводится полное предупреждение –
SLF4J: No SLF4J providers were found. SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.
Classpath содержит привязки SLF4J для версий slf4j-api до 1.8
Если вы используете версию SLF4J 1.8 и у вас есть привязки предыдущих версий в classpath, но не привязки 1.8, вы увидите предупреждение, как показано ниже.
SLF4J: No SLF4J providers were found. SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details. SLF4J: Class path contains SLF4J bindings targeting slf4j-api versions prior to 1.8. SLF4J: Ignoring binding found at [jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/ slf4j-1.7.25/slf4j-jdk14-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#ignoredBindings for an explanation.
NoClassDefFoundError: org / apache / commons / logging / LogFactory
Если вы работаете с slf4j-jcl и у вас есть только slf4j-jcl.jar в вашем пути к классам, вы получите исключение, такое как приведенное ниже.
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at org.slf4j.impl.JCLLoggerFactory.getLogger(JCLLoggerFactory.java:77) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:358) at SLF4JExample.main(SLF4JExample.java:8) Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory 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) . 3 more
Чтобы решить эту проблему, вам нужно добавить commons-logging.jar к вашему classpath.
Обнаружил как jcl-over-slf4j.jar, так и связанный slf4j-jcl.jar на пути к классам.
Привязка slf4j-jcl.jar перенаправляет вызовы регистратора slf4j в JCL, а jcl-over-slf4j.jar перенаправляет вызовы регистратора JCL в slf4j. Таким образом, вы не можете иметь оба в classpath вашего проекта. Если вы сделаете это, вы получите исключение, такое как приведенное ниже.
SLF4J: Detected both jcl-over-slf4j.jar AND bound slf4j-jcl.jar on the class path, preempting StackOverflowError. SLF4J: See also http://www.slf4j.org/codes.html#jclDelegationLoop for more details. Exception in thread "main" java.lang.ExceptionInInitializerError at org.slf4j.impl.StaticLoggerBinder.(StaticLoggerBinder.java:71) at org.slf4j.impl.StaticLoggerBinder.(StaticLoggerBinder.java:42) at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150) at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124) at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357) at SLF4JExample.main(SLF4JExample.java:8) Caused by: java.lang.IllegalStateException: Detected both jcl-over-slf4j.jar AND bound slf4j-jcl.jar on the class path, preempting StackOverflowError. See also http://www.slf4j.org/codes.html#jclDelegationLoop for more details. at org.slf4j.impl.JCLLoggerFactory.(JCLLoggerFactory.java:54) . 7 more
Чтобы решить эту проблему, удалите любой из файлов JAR.
Обнаружено несоответствие имени регистратора
Вы можете создать объект Logger с помощью –
- Передача имени созданного регистратора в качестве аргумента методу getLogger () .
- Передача класса в качестве аргумента этому методу.
Передача имени созданного регистратора в качестве аргумента методу getLogger () .
Передача класса в качестве аргумента этому методу.
Если вы пытаетесь создать объект фабрики регистратора, передавая класс в качестве аргумента, и если вы установили системное свойство slf4j.detectLoggerNameMismatch в значение true, тогда имя класса, которое вы передаете в качестве аргумента методу getLogger () и используемый вами класс должен быть таким же, в противном случае вы получите следующее предупреждение –
«Обнаружено несоответствие имени регистратора.
Рассмотрим следующий пример.
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SLF4JExample public static void main(String[] args) System.setProperty("slf4j.detectLoggerNameMismatch", "true"); //Creating the Logger object Logger logger = LoggerFactory.getLogger(Sample.class); //Logging the information logger.info("Hi Welcome to Tutorilspoint"); > >
Здесь мы установили для свойства slf4j.detectLoggerNameMismatch значение true. Имя класса, которое мы использовали, – SLF4JExample, а имя класса, которое мы передали методу getLogger (), – Sample, так как они оба не равны, мы получим следующее предупреждение.
SLF4J: Detected logger name mismatch. Given name: "Sample"; computed name: "SLF4JExample". SLF4J: See http://www.slf4j.org/codes.html#loggerNameMismatch for an explanation Dec 10, 2018 12:43:00 PM SLF4JExample main INFO: Hi Welcome to Tutorilspoint
Примечание – это происходит после slf4j 1.7.9
Classpath содержит несколько привязок SLF4J.
У вас должна быть только одна привязка в пути к классам. Если у вас есть несколько привязок, вы получите предупреждение с указанием привязок и их местоположения.
Предположим, что если у нас есть привязки slf4j-jdk14.jar и slf4j-nop.jar в пути к классам, мы получим следующее предупреждение.
SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/ slf4j-1.7.25/slf4j-nop-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/ slf4j-1.7.25/slf4j-jdk14-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF4J: Actual binding is of type [org.slf4j.helpers.NOPLoggerFactory]
Обнаружены оба log4j-over-slf4j.jar И привязанные slf4j-log4j12.jar на пути к классам
Чтобы перенаправить вызовы log4j logger в slf4j, вам нужно использовать привязку log4j-over-slf4j.jar, а если вы хотите перенаправить вызовы slf4j в log4j, вам необходимо использовать привязку slf4j-log4j12.jar .
Таким образом, вы не можете иметь оба в classpath. Если вы это сделаете, вы получите следующее исключение.
How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
Problem: You are getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory in your Java program, which uses a logging framework to log messages into a log file. It could be direct dependency or indirect dependency due to any framework e.g. Spring, Hibernate, or any open-source library like jackson or any other JSON parsing library.
Cause : java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory error comes when you are using Apache commons-logging directly or indirectly using frameworks like Hibernate, Spring and commons-logging-1.1.2.jar are not available in CLASSPATH. Sometimes this may be due to some nasty classpath issue, but most often this is due to missing JAR in the classpath.
Solution: If it’s a case of a missing JAR file then issues will be solved as soon as you deploy the commons-logging-1.1.1.jar or commons-logging-1.1.2.jar in CLASSPATH, but deploying JAR manually is tedious and error-prone.
You need to first find those JAR files on the internet and then hope that there is no version mismatch error e.g. suppose your Spring or Hibernate version is using Apache commons-logging version 1.1.2 and you deployed version 1.1.1, you might not detect any error upfront but it will fail in production as soon as a new feature which is only available in commons-logging-1.1.2.jar is triggered.
That’s why it’s best to use Maven to download and manage dependency JAR files. Maven will not only automatically download the JAR file for you but also it will ensure that the correct versions of transitive dependent JARs are downloaded.
In order to add commons-logging JAR using Maven, you can add the following dependency in your pom.xml
dependency> groupId>commons-logging groupId> artifactId>commons-logging artifactId> version>1.2 version> dependency>
If you are using Maven in Eclipse using the M2Eclipse plugin, You can even search and add dependencies like below :
For manual download, you can go to the maven central website and download the commons-logging.jar file. http://repo1.maven.org/maven2/commons-logging/commons-logging/1.1.2/commons-logging-1.1.2.jar
You can even download apache commons-logging JARs from the Apache Commons Logging website as well, http://commons.apache.org/logging/download_logging.cgi as well.
That’s all about how to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory error in Java. It can come even if you are not using commons-logging directly but using a library like Spring, Hibernate, or Struts, which internally uses this library for their logging need. This error should be fixed as soon as you put the commons-logging-1.1.1.jar file in your CLASSPATH.
Related tutorials and guides to deal with different errors and exceptions in Java :
- How to fix java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject Error? [solution]
- How to solve java.lang.NoClassDefFoundError: org/dom4j/DocumentException [solution]
- What is difference between ClassNotFoundException and NoClassDefFoundError in Java? [answer]
- How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Java? [answer]
- How to fix java.lang.unsupportedclassversionerror unsupported major.minor version 49.0 50.0 51.0 in Java [solution]
- How to Fix java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver [solution]
- ‘javac’ is not recognized as an internal or external command, operable program, or batch file [solution]
If you see this error even after having commons-logging.jar then it means your CLASSPATH is not set properly. Follow the steps given in this article to set up your CLASSPATH properly.
1 comment:
I am getting following exception while trying to write a simple Spring HelloWorld application using Spring 4.2.1 version using autowiring and annotation config application context.
Exception in thread «main» java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.springframework.context.support.AbstractApplicationContext.(AbstractApplicationContext.java:158)
at org.springframework.context.support.GenericApplicationContext.(GenericApplicationContext.java:102)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.(AnnotationConfigApplicationContext.java:60)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.(AnnotationConfigApplicationContext.java:82)
at hello.Application.main(Application.java:21)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
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)
. 5 more
I have spring-core-4.2.1.RELEASE.jar, spring-context-4.2.1.RELEASE.jar and spring-beans-4.2.1.RELEASE.jar in my Eclipse build path as referenced libraries.
Do I simply download latest version of apache commons logging library and put it on classpath? Or spring 4.2.1 has dependency on any specific version of Apache commons logging JAR?