以编程方式更改 Log4j2 中的日志级别

问题描述 投票:0回答:9

我对以编程方式更改 Log4j2 中的日志级别感兴趣。我尝试查看他们的配置文档,但似乎没有任何内容。我也尝试查看包裹:

org.apache.logging.log4j.core.config
,但里面也没有任何有用的东西。

java log4j2
9个回答
230
投票

最简单的方法:

根据 log4j2 版本 2.4 常见问题解答进行编辑

您可以使用 Log4j Core 中的配置器类设置记录器的级别。 但是请注意,Configurator 类不是公共 API 的一部分。

// org.apache.logging.log4j.core.config.Configurator;
Configurator.setLevel("com.example.Foo", Level.DEBUG);

// You can also set the root logger:
Configurator.setRootLevel(Level.DEBUG);

来源

首选方式:

已编辑以反映 Log4j2 版本 2.0.2 中引入的 API 的更改

如果您想更改根记录器级别,请执行以下操作:

LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); 
loggerConfig.setLevel(level);
ctx.updateLoggers();  // This causes all Loggers to refetch information from their LoggerConfig.

这里是 LoggerConfig 的 javadoc。


75
投票

@slaadvak 接受的答案对于我的 Log4j2 2.8.2 不起作用。以下是这样做的。

要更改日志

Level
通用使用:

Configurator.setAllLevels(LogManager.getRootLogger().getName(), level);

要仅更改当前类别的日志

Level
,请使用:

Configurator.setLevel(LogManager.getLogger(CallingClass.class).getName(), level);

20
投票

我在这里找到了一个很好的答案:https://garygregory.wordpress.com/2016/01/11/changing-log-levels-in-log4j2/

您可以使用 org.apache.logging.log4j.core.config.Configurator 设置特定记录器的级别。

Logger logger = LogManager.getLogger(Test.class);
Configurator.setLevel(logger.getName(), Level.DEBUG);

19
投票

如果您想更改单个特定记录器级别(不是根记录器或配置文件中配置的记录器),您可以执行以下操作:

public static void setLevel(Logger logger, Level level) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();

    LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName());
    LoggerConfig specificConfig = loggerConfig;

    // We need a specific configuration for this logger,
    // otherwise we would change the level of all other loggers
    // having the original configuration as parent as well

    if (!loggerConfig.getName().equals(logger.getName())) {
        specificConfig = new LoggerConfig(logger.getName(), level, true);
        specificConfig.setParent(loggerConfig);
        config.addLogger(logger.getName(), specificConfig);
    }
    specificConfig.setLevel(level);
    ctx.updateLoggers();
}

8
投票

默认情况下,大多数答案都假设日志记录必须是可加的。但是假设某个包正在生成大量日志,并且您只想关闭该特定记录器的日志记录。这是我用来让它工作的代码

    public class LogConfigManager {

    public void setLogLevel(String loggerName, String level) {
        Level newLevel = Level.valueOf(level);
        LoggerContext logContext = (LoggerContext) LogManager.getContext(false);
        Configuration configuration = logContext.getConfiguration();
        LoggerConfig loggerConfig = configuration.getLoggerConfig(loggerName);
        // getLoggerConfig("a.b.c") could return logger for "a.b" if there is no logger for "a.b.c"
        if (loggerConfig.getName().equalsIgnoreCase(loggerName)) {
            loggerConfig.setLevel(newLevel);
            log.info("Changed logger level for {} to {} ", loggerName, newLevel);
        } else {
            // create a new config.
            loggerConfig = new LoggerConfig(loggerName, newLevel, false);
            log.info("Adding config for: {} with level: {}", loggerConfig, newLevel);
            configuration.addLogger(loggerName, loggerConfig);


            LoggerConfig parentConfig = loggerConfig.getParent();
            if (parentConfig != null) {
                do {
                    for (Map.Entry<String, Appender> entry : parentConfig.getAppenders().entrySet()) {
                        loggerConfig.addAppender(entry.getValue(), null, null);
                    }
                    parentConfig = parentConfig.getParent();
                } while (null != parentConfig && parentConfig.isAdditive());
            }
        }
        logContext.updateLoggers();
    }
}

相同的测试用例

public class LogConfigManagerTest {
    @Test
    public void testLogChange() throws IOException {
        LogConfigManager logConfigManager = new LogConfigManager();
        File file = new File("logs/server.log");
        Files.write(file.toPath(), new byte[0], StandardOpenOption.TRUNCATE_EXISTING);
        Logger logger = LoggerFactory.getLogger("a.b.c");
        logger.debug("Marvel-1");
        logConfigManager.setLogLevel("a.b.c", "debug");
        logger.debug("DC-1");
        // Parent logger level should remain same
        LoggerFactory.getLogger("a.b").debug("Marvel-2");
        logConfigManager.setLogLevel("a.b.c", "info");
        logger.debug("Marvel-3");
        // Flush everything
        LogManager.shutdown();

        String content = Files.readAllLines(file.toPath()).stream().reduce((s1, s2) -> s1 + "\t" + s2).orElse(null);
        Assert.assertEquals(content, "DC-1");
    }
}

假设以下 log4j2.xml 在类路径中

<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns="http://logging.apache.org/log4j/2.0/config">

    <Appenders>
        <File name="FILE" fileName="logs/server.log" append="true">
            <PatternLayout pattern="%m%n"/>
        </File>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%m%n"/>
        </Console>
    </Appenders>

    <Loggers>
        <AsyncLogger name="a.b" level="info">
            <AppenderRef ref="STDOUT"/>
            <AppenderRef ref="FILE"/>
        </AsyncLogger>

        <AsyncRoot level="info">
            <AppenderRef ref="STDOUT"/>
        </AsyncRoot>
    </Loggers>

</Configuration>

6
投票

对于那些仍在为此苦苦挣扎的人,我必须将类加载器添加到“getContext()”调用中:

  log.info("Modifying Log level! (maybe)");
  LoggerContext ctx = (LoggerContext) LogManager.getContext(this.getClass().getClassLoader(), false);
  Configuration config = ctx.getConfiguration();
  LoggerConfig loggerConfig = config.getLoggerConfig("com.cat.barrel");
  loggerConfig.setLevel(org.apache.logging.log4j.Level.TRACE);
  ctx.updateLoggers();

我在测试中添加了一个 jvm 参数:-Dlog4j.debug。这会为 log4j 执行一些详细的日志记录。 我注意到最终的 LogManager 不是我正在使用的那个。 砰,添加类加载器,你就可以开始比赛了。


4
投票

程序化方法相当具有侵入性。也许你应该检查 Log4J2 提供的 JMX 支持:

  1. 在应用程序启动时启用 JMX 端口:

    -Dcom.sun.management.jmxremote.port=[port_num]

  2. 执行应用程序时,使用任何可用的 JMX 客户端(JVM 在 JAVA_HOME/bin/jconsole.exe 中提供一个客户端)。

  3. 在 JConsole 中查找“org.apache.logging.log4j2.Loggers”bean

  4. 最后更改记录器的级别

我最喜欢的一点是您不必修改代码或配置来管理它。一切都是外部的、透明的。

更多信息:http://logging.apache.org/log4j/2.x/manual/jmx.html


2
投票

我发现的一种不寻常的方法是创建两个具有不同日志记录级别的单独文件。
例如。 log4j2.xml 和 log4j-debug.xml 现在从此文件更改配置。
示例代码:

ConfigurationFactory configFactory = XmlConfigurationFactory.getInstance();
            ConfigurationFactory.setConfigurationFactory(configFactory);
            LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = classloader.getResourceAsStream(logFileName);
            ConfigurationSource configurationSource = new ConfigurationSource(inputStream);

            ctx.start(configFactory.getConfiguration(ctx, configurationSource));

-4
投票

截至 2023 年,上述内容似乎不起作用(或者我会说至少对我来说似乎不起作用),有效的是以下

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;

final LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
final Logger logger = loggerContext.exists(org.slf4j.Logger.ROOT_LOGGER_NAME); // give it your logger name
final Level newLevel = Level.toLevel("ERROR", null); // give it your log level
logger.setLevel(newLevel);

如果您想了解如何在每个请求的基础上执行此操作,请参阅我对帖子的评论更改每个请求的 log4j 中的优先级

© www.soinside.com 2019 - 2024. All rights reserved.