我有兴趣以编程方式更改Log4j2中的日志级别.我试着查看他们的配置文档,但似乎没有任何东西.我也试着查看包裹:org.apache.logging.log4j.core.config
但是那里的任何东西看起来都没有帮助.
sla*_*vak 122
根据log4j2版本2.4 FAQ编辑
您可以使用Log4j Core中的类Configurator设置记录器的级别.但请注意,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);
Run Code Online (Sandbox Code Playgroud)
已编辑以反映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.
Run Code Online (Sandbox Code Playgroud)
这是LoggerConfig的javadoc.
4my*_*yle 28
@slaadvak接受的答案对我来说对Log4j2 2.8.2不起作用.以下做了.
要更改日志Level
普遍使用:
Configurator.setAllLevels(LogManager.getRootLogger().getName(), level);
Run Code Online (Sandbox Code Playgroud)
要Level
仅更改当前类的日志,请使用:
Configurator.setLevel(LogManager.getLogger(CallingClass.class).getName(), level);
Run Code Online (Sandbox Code Playgroud)
Jör*_*ich 18
如果要更改单个特定记录器级别(不是配置文件中配置的根记录器或记录器),可以执行以下操作:
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();
}
Run Code Online (Sandbox Code Playgroud)
小智 10
我在这里找到了一个很好的答案: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);
Run Code Online (Sandbox Code Playgroud)
默认情况下,大多数答案都假设日志记录必须是可加的。但是假设某个包正在生成大量日志,并且您只想关闭该特定记录器的日志记录。这是我用来让它工作的代码
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();
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();
}
}
Run Code Online (Sandbox Code Playgroud)
相同的测试用例
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");
}
}
Run Code Online (Sandbox Code Playgroud)
假设以下 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>
Run Code Online (Sandbox Code Playgroud)
程序化方法相当具有侵入性。也许您应该检查 Log4J2 提供的 JMX 支持:
在应用程序启动时启用 JMX 端口:
-Dcom.sun.management.jmxremote.port=[port_num]
在执行应用程序时使用任何可用的 JMX 客户端(JVM 在 JAVA_HOME/bin/jconsole.exe 中提供了一个)。
在 JConsole 中查找“org.apache.logging.log4j2.Loggers”bean
最后更改记录器的级别
我最喜欢的一点是您不必修改代码或配置来管理它。这一切都是外部的和透明的。
更多信息:http : //logging.apache.org/log4j/2.x/manual/jmx.html
对于那些仍在为此苦苦挣扎的人,我必须将类加载器添加到“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();
Run Code Online (Sandbox Code Playgroud)
我在测试中添加了一个 jvm 参数:-Dlog4j.debug 。这会为 log4j 执行一些详细的日志记录。我注意到最终的 LogManager 不是我正在使用的那个。砰,添加类加载器,您就可以开始比赛了。