【问题标题】:Error log is displayed in console for log4j2 after using LoggerContext使用 LoggerContext 后 log4j2 的控制台中显示错误日志
【发布时间】:2020-06-19 13:23:35
【问题描述】:

我正在使用 LoggerContext 在代码中设置 log4j2,xml 路径并得到 No log4j2 configuration file found 错误日志。

代码

    LoggerContext context = (org.apache.logging.log4j.core.LoggerContext)LogManager.getContext(false);
    String  fileName = "\\resources\\log4j2.xml";
    context.setConfigLocation(new File(fileName).toURI());
    LOG.debug("This Will Be Printed On Debug");
    LOG.info("This Will Be Printed On Info");
    LOG.warn("This Will Be Printed On Warn");

输出

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only 
errors to the console. Set system property 'org.apache.logging.log4j.simplelog.StatusLogger.level' to 
TRACE to show Log4j2 internal initialization logging.
DEBUG | 2020-06-19 14:16:21 | [main] | (Log4j2Example.java:22) - This Will Be Printed On Debug
INFO  | 2020-06-19 14:16:21 | [main] | (Log4j2Example.java:23) - This Will Be Printed On Info
WARN  | 2020-06-19 14:16:21 | [main] | (Log4j2Example.java:24) - This Will Be Printed On Warn

在这里我得到了预期的结果,但在开始时也得到了错误日志。 如果我在 eclipse 的类路径中设置 log4j2,xml 则不会显示错误。

我们如何在使用 LoggerContext 时删除错误日志?

【问题讨论】:

  • 我不确定这是否能解决您的问题,因为我并没有真正研究它,但我认为您似乎在 org.apache.logging 之前缺少一个“(” .. .
  • @maloomeister 拼写错误。我已经更正了。

标签: java logging log4j2


【解决方案1】:

当您调用 LogManager.getContext(false) 时,Log4j 将进行初始化。这会导致 No log4j2 configuration file found 消息,因为您还没有配置一个。

尝试使用Configurator.initialize("My Config", "\\resources\\log4j2.xml");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多