Make Sure Log Messages Show Up (Programmatically)

Here’s a quick snippet that shows how, using java.util.logging, to ensure that log messages actually show up on your console without the hassle of editing or specifying a logging.properties file somewhere.  This is useful particularly for unit tests featuring the javax.ejb.embeddable.EJBContainer class.


final Logger topLogger = Logger.getLogger("");
assert topLogger != null;
Handler consoleHandler = null;
final Handler[] handlers = topLogger.getHandlers();
if (handlers != null && handlers.length > 0) {
for (final Handler handler : topLogger.getHandlers()) {
if (handler instanceof ConsoleHandler) {
consoleHandler = handler;
break;
}
}
}
if (consoleHandler == null) {
consoleHandler = new ConsoleHandler();
topLogger.addHandler(consoleHandler);
}
consoleHandler.setLevel(Level.FINEST);

Author: Laird Nelson

Devoted husband and father; working on Helidon at the intersection of Java, Jakarta EE, architecture, Kubernetes and microservices at Oracle; open source guy; Hammond B3 player and Bainbridge Islander.

%d bloggers like this: