Logger And Handler Level Gates
Set levels on loggers and handlers separately: a record must pass both gates, and setUseParentHandlers(false) stops duplicated parent output.
Code
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogLevelFiltering {
public static void main(String[] args) {
Logger audit = Logger.getLogger("app.audit");
Logger child = Logger.getLogger("app.audit.payment");
// the logger level gates first: a child logger with no explicit level inherits its parent's
audit.setLevel(Level.WARNING);
child.setLevel(Level.INFO);
audit.info("below warning, dropped"); // blocked by the level, nothing is emitted
audit.warning("audit trail kept"); // passes and travels up the logger chain to the root handler
// two gates: logger level first, then handler level
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.SEVERE);
child.addHandler(handler);
child.setUseParentHandlers(false); // stop parent propagation so records are not emitted twice
child.info("logger ok, handler drops"); // passes the logger level, then stops at the handler level
child.severe("passes both gates"); // passes both gates
for (Handler attached : child.getHandlers()) {
System.out.println("attached: " + attached.getClass().getSimpleName());
}
}
}How it works
The working surface is the class LogLevelFiltering and the function main — everything else is wiring.
One loop does the cycling here: for (Handler attached : child.getHandlers()).
Putting it to use
Output lines are prefixed (attached:), making each step’s effect easy to spot.
Core lines
audit.warning("audit trail kept"); // passes and travels up the logger chain to the root handler
// two gates: logger level first, then handler level
ConsoleHandler handler = new ConsoleHandler();
child.info("logger ok, handler drops"); // passes the logger level, then stops at the handler level
child.severe("passes both gates"); // passes both gates
for (Handler attached : child.getHandlers()) {
System.out.println("attached: " + attached.getClass().getSimpleName());
}
Logger child = Logger.getLogger("app.audit.payment");
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does Logger And Handler Level Gates print when run?
- The script runs standalone; its 1 labeled outputs include `attached:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.