← 中文资源

简体中文版本

Logger 与 Handler 的双重级别门槛

Logger 与 Handler 各有独立级别,日志要先过 logger 级别再过 handler 级别;setUseParentHandlers(false) 关掉父级传播,避免同一行重复输出。

阅读英文原文

实现说明

全部逻辑都在类 LogLevelFiltering和函数 main中。 这个示例中仅有的重复出现在 for (Handler attached : child.getHandlers()) 里。

使用要点

  • 直接运行文件,输出会带上标签,比如 attached:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「Logger 与 Handler 的双重级别门槛」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 attached: 这类标签。

核心语句

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");

代码示例

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());
        }
    }
}