-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from ymesika/test-utils-log4j
Added support for Log4j test utils
- Loading branch information
Showing
3 changed files
with
52 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
test-utils/src/log4j/java/com/slimgears/util/test/logging/Log4jLogLevelListener.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package com.slimgears.util.test.logging; | ||
|
||
import com.google.auto.service.AutoService; | ||
import com.google.common.base.Strings; | ||
import org.apache.logging.log4j.Level; | ||
import org.apache.logging.log4j.LogManager; | ||
import org.apache.logging.log4j.core.LoggerContext; | ||
import org.apache.logging.log4j.core.config.Configuration; | ||
import org.apache.logging.log4j.core.config.LoggerConfig; | ||
|
||
import java.util.Optional; | ||
|
||
@AutoService(LogLevelListener.class) | ||
public class Log4jLogLevelListener implements LogLevelListener { | ||
@Override | ||
public Rollback onSetLogLevel(String loggerName, LogLevel logLevel) { | ||
return Optional | ||
.of(setLogLevel(loggerName, logLevel)) | ||
.orElseGet(Rollback::empty); | ||
} | ||
|
||
private Rollback setLogLevel(String loggerName, LogLevel level) { | ||
LoggerContext context = (LoggerContext) LogManager.getContext(false); | ||
Configuration config = context.getConfiguration(); | ||
LoggerConfig loggerConfig = config.getLoggerConfig(Strings.isNullOrEmpty(loggerName) ? LogManager.ROOT_LOGGER_NAME : loggerName); | ||
Level newLevel = Level.toLevel(level.name()); | ||
Level prevLevel = loggerConfig.getLevel(); | ||
loggerConfig.setLevel(newLevel); | ||
context.updateLoggers(); | ||
return () -> { | ||
loggerConfig.setLevel(prevLevel); | ||
context.updateLoggers(); | ||
}; | ||
} | ||
} |