Skip to content

Commit

Permalink
Merge pull request #263 from Vlatombe/improve-loggerrule
Browse files Browse the repository at this point in the history
LoggerRule improvements
  • Loading branch information
jglick authored Nov 13, 2020
2 parents 892fe37 + 5006c90 commit a312031
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions src/main/java/org/jvnet/hudson/test/LoggerRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,12 @@
*/
public class LoggerRule extends ExternalResource {

private final Handler consoleHandler = new ConsoleHandler();
private final Handler consoleHandler = new ConsoleHandlerWithMaxLevel();
private final Map<Logger,Level> loggers = new HashMap<>();
// initialized iff capture is called:
// initialized if and only if capture is called:
private RingBufferLogHandler ringHandler;
private List<String> messages;
private boolean verbose = true;

/**
* Initializes the rule, by default not recording anything.
Expand All @@ -72,6 +73,14 @@ public LoggerRule() {
consoleHandler.setLevel(Level.ALL);
}

/**
* Don't emit logs to the console, only record.
*/
public LoggerRule quiet() {
this.verbose = false;
return this;
}

/**
* Initializes log record capture, in addition to merely printing it.
* This allows you to call {@link #getRecords} and/or {@link #getMessages} later.
Expand Down Expand Up @@ -114,7 +123,9 @@ public synchronized void publish(LogRecord record) {
public LoggerRule record(Logger logger, Level level) {
loggers.put(logger, logger.getLevel());
logger.setLevel(level);
logger.addHandler(consoleHandler);
if (verbose) {
logger.addHandler(consoleHandler);
}
if (ringHandler != null) {
logger.addHandler(ringHandler);
}
Expand Down Expand Up @@ -173,7 +184,9 @@ protected void after() {
for (Map.Entry<Logger,Level> entry : loggers.entrySet()) {
Logger logger = entry.getKey();
logger.setLevel(entry.getValue());
logger.removeHandler(consoleHandler);
if (verbose) {
logger.removeHandler(consoleHandler);
}
if (ringHandler != null) {
logger.removeHandler(ringHandler);
}
Expand Down Expand Up @@ -284,4 +297,22 @@ public void describeTo(org.hamcrest.Description description) {
}
}

/**
* Delegates to the given Handler but filter out records higher or equal to its initial level
*/
private static class ConsoleHandlerWithMaxLevel extends ConsoleHandler {
private final Level initialLevel;

public ConsoleHandlerWithMaxLevel() {
super();
initialLevel = getLevel();
}

@Override
public void publish(LogRecord record) {
if (record.getLevel().intValue() < initialLevel.intValue()) {
super.publish(record);
}
}
}
}

0 comments on commit a312031

Please sign in to comment.