【问题标题】:Log4j-2.6.2 Basic Configurator is not configuring the logging levelsLog4j-2.6.2 基本配置器未配置日志记录级别
【发布时间】:2016-09-04 22:22:45
【问题描述】:

我试图通过以下代码实现一个基本的配置器

package com.myapp.loggingutilities;

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

public class LoggingUtilitiesApplication {
    static Logger currentLogger = Logger.getLogger(LoggingUtilitiesApplication.class);

    public static void main(String[] args) {
        BasicConfigurator.configure();
        currentLogger.debug("Application Started here");
        LoggerUtilityModel bar = new LoggerUtilityModel();
        bar.doIt();
        currentLogger.debug("Application ended");

    }
}

bar 的类定义是

package com.myapp.loggingutilities;
import org.apache.log4j.Logger;

public class LoggerUtilityModel {
    static Logger modelLogger = Logger.getLogger(LoggerUtilityModel.class);

    public void doIt() {
        modelLogger.debug("OPPS! DID IT AGAIN");
    }

}

我使用的是 Log4j2,分发版是 here。当我在构建路径中有 Log4j-to-slf4j 和实现 jar 时,我总是收到 SLF4J 桥接错误:

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext
    at org.apache.log4j.Logger$PrivateManager.getContext(Logger.java:59)

当我删除它们时,一切正常。但是日志消息没有被打印出来

我认为BasicConfigurator 应该为 DEBUG 配置根记录器,因此我的所有日​​志语句都应该通过(即任何高于或高于 DEBUG 级别的内容)。但是当我运行应用程序时,我在控制台上看不到任何日志消息。我错过了什么?

【问题讨论】:

  • 我刚刚运行了你的代码,并在控制台中得到了 DEBUG 级别的相应消息。
  • @DimaSan 我碰巧从我的构建路径中删除了 slf4j 绑定 jar,因为它们抱怨冲突 - 你也这样做了吗?
  • 我认为问题在于缺少slf4j jars,因为我使用已经包含它的 Spring Boot 运行您的代码。
  • @DimaSan 我自己运行了应用程序,当我在路径上有 SLF4J jar 时绑定不起作用。我不打算用 Spring 运行。
  • 我刚刚创建了一个新的 Java 项目,并将唯一的一个 jar Apache Log4j 1.2.17 添加到我的构建路径中,它可以工作。

标签: java logging configuration log4j log4j2


【解决方案1】:

BasicConfigurator 是 log4j 1.2 类,不能用于配置 Log4j 2。基本上,org.apache.log4j 包中的所有内容都是 Log4j 1.2(旧),org.apache.logging.log4j 命名空间中的所有内容都是用于 Log4j 2。

如果您对 Log4j 2 的编程配置感兴趣,请参阅the manual page。就我个人而言,我发现新的简化 XML 配置文件格式最容易使用。

您看到的行为(仅在 ERROR 级别进行控制台日志记录)是 Log4j 2 的“默认配置”,如果找不到配置文件并且没有手动配置,它会执行此操作。

【讨论】:

  • @RemkoPompa 感谢您的答复。但是为什么 1.2 有 DEBUG 而 2.x 有 ERROR 仍然没有意义。我期待这个原因被记录在某个地方。还有,
【解决方案2】:

问题似乎是为 log4j2.6.2 设置的 LEVEL。根据 Apache 的 Log4J-2.6.2 文档,所有默认日志消息都设置为 DEBUG。

此外,您不能使用根记录器更改日志记录级别。您需要为每个记录器更改它。一切都默认为 ERROR。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-08
    • 2011-07-24
    • 2017-06-04
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多