简体   繁体   中英

Understanding java logger - Different output for almost identical code

The first piece of code is doing almost exactly the same thing as the second one. But the hierarchal propagation of Log record is different. Can someone please explain why its happening. Thanks

Logger log1 = Logger.getLogger("Test1");
        Logger log2 = Logger.getLogger("Test1.Test2");
        Logger log3 = Logger.getLogger("Test1.Test2.Test3");
        log2.setLevel(Level.WARNING);
        log3.setLevel(Level.INFO);
        log2.addHandler(new ConsoleHandler());
        log3.addHandler(new ConsoleHandler());
        log1.log(Level.INFO, "Message By: {0}",log1.getName());
        log2.log(Level.INFO, "Message By: {0}",log2.getName());
        log3.log(Level.INFO, "Message By: {0}",log3.getName());

OUTPUT: Nov 27, 2014 8:32:51 PM Test main
INFO: Message By: Test1
Nov 27, 2014 8:32:51 PM Test main
INFO: Message By: Test1.Test2.Test3
Nov 27, 2014 8:32:51 PM Test main
INFO: Message By: Test1.Test2.Test3
Nov 27, 2014 8:32:51 PM Test main
INFO: Message By: Test1.Test2.Test3

Logger logger      = Logger.getLogger("d");
        Logger logger1     = Logger.getLogger("d.1");
        Logger logger1_2   = Logger.getLogger("d.1.2");
        logger1  .setLevel(Level.WARNING);
        logger1_2.setLevel(Level.INFO);
        logger     .info("msg:");
        logger1    .info("msg: 1");
        logger1_2  .info("msg: 1.2");
OUTPUT:
Nov 27, 2014 8:33:34 PM Test main
INFO: msg:
Nov 27, 2014 8:33:34 PM Test main
INFO: msg: 1.2

The lowest logger INFO message should not have propagated to the top as the middle one is set to Warning

That assumption is the source of your confusion. Record propergation is decsribed in the java.util.logging.Logger class documentation. Per the documentation:

By default, loggers also publish to their parent's Handlers, recursively up the tree.

The child logger is directly logging to the parent handler not the parent logger. So the level of the parent handler is what comes in to play not the level of the parent logger in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM