extends java.util.logging.Logger not working

让人想犯罪 __ 提交于 2019-12-02 04:36:17

As @leonbloy and @E-Riz pointed out, per the documentation:

Therefore, any subclasses of Logger (unless they are implemented in conjunction with a new LogManager class) should take care to obtain a Logger instance from the LogManager class and should delegate operations such as "isLoggable" and "log(LogRecord)" to that instance. Note that in order to intercept all logging output, subclasses need only override the log(LogRecord) method. All the other logging methods are implemented as calls on this log(LogRecord) method.

So here would be an example that must be run with -Djava.util.logging.manager=bad.idea.OdiousLogManager so the JVM uses the new LogManager:

package bad.idea;

import java.awt.Toolkit;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class OdiousLogManager extends LogManager {

    @Override
    public synchronized Logger getLogger(String name) {
        Logger l = super.getLogger(name);
        if (l == null) {
            l = new AbhorentLogger(name, null);
            super.addLogger(l);
        }
        return l;
    }


    private static class AbhorentLogger extends Logger {

        AbhorentLogger(String name, String resourceBundleName) {
            super(name, resourceBundleName);
        }

        @Override
        public void log(LogRecord record) {
            super.log(record);
            mightyCatHearMeRoar(record);
        }

        private void mightyCatHearMeRoar(LogRecord record) {
            if (super.isLoggable(record.getLevel())) {
                Toolkit.getDefaultToolkit().beep();
            }
        }
    }


    //...
    private static final Logger logger = Logger.getLogger("godaweful");
    public static void main(String[] args) {
        logger.severe(logger.getClass().getName());
    }
}

If you only want to listen to events then you should simply implement a custom handler and avoid extending logger.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!