【问题标题】:How to resolve this "ClassNotFoundException" error如何解决此“ClassNotFoundException”错误
【发布时间】:2020-03-06 11:32:52
【问题描述】:

你好,我收到了这个错误

错误:无法找到或加载主类 Log4jEx.BasicConfiguratorEx 引起:java.lang.ClassNotFoundException: Log4jEx.BasicConfiguratorEx

这是我的程序

package Log4jEx;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class BasicConfiguratorEx {

    static Logger logger = Logger.getLogger(BasicConfiguratorEx.class); 
    //Creating object for Logger without NEW//

    public static void main(String[] args) {            
        BasicConfigurator.configure();
        logger.debug("This is a debug");
        logger.info("This is a info");
        logger.warn("This is a warn");
        logger.fatal("This is a fatal message");    
    }    
}

【问题讨论】:

  • java !== javascript
  • 通过将该类添加到类路径
  • 您在何时何地收到此错误?在您的 IDE 中,在编译期间,在启动期间?
  • @WesleyDeKeirsmaeker 在编译期间

标签: java log4j classnotfoundexception classnotfound


【解决方案1】:

log4j 1.x

BasicConfigurator 是 log4j 1.2 类,不能用于配置 Log4j 2。

Log4j 1.x 的生命周期已经结束

如果你想在你的项目中使用 BasicConfigurator。

  1. 从此website下载log4j 1.2 jar。
  2. 将 log4j-1.2.17 作为外部 jar 文件添加到您的项目构建路径中。

log4j 2.x

不需要 BasicConfigurator 类。

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

public class HelloWorld {
    private static final Logger logger = LogManager.getLogger("HelloWorld");
    public static void main(String[] args) {
        logger.debug("This is debug message");
        logger.info("This is info message");
        logger.warn("This is warn message");
        logger.fatal("This is fatal message");
        logger.error("This is error message");
        System.out.println("Executed successfully....");

    }
}

output:
This is debug message
This is info message
This is warn message
This is fatal message
This is error message
Logic executed successfully....

在 src/main/resources 下添加 log4j2.properties 文件

name=PropertiesConfig

rootLogger.level=debug
rootLogger.appenderRefs=stdout
rootLogger.appenderRef.stdout.ref=StandardOutput

appenders=console

#log messages to terminal
appender.console.type=Console
appender.console.name=StandardOutput

在 pom.xml 中添加以下依赖项

<dependency>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-api</artifactId>
   <version>2.13.1</version>
</dependency>
<dependency>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-core</artifactId>
   <version>2.13.1</version>
</dependency>

我希望这会有所帮助。

【讨论】:

  • @SarathKumar 我已经更新了解决方案。我希望它应该工作。如果没有,请告诉我。
  • @SarathKumar 现在您可以在项目中将 log4j 1.x 与 BasicConfiguratorEx 或 lo4j 2.x 一起使用。
猜你喜欢
  • 1970-01-01
  • 2017-12-12
  • 2012-02-14
  • 2015-04-12
  • 2016-06-21
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多