How can I disable the default console handler, while using the java logging API?

前端 未结 5 2016
天涯浪人
天涯浪人 2020-11-27 12:07

Hi I am trying to implement the java logging in my application. I want to use two handlers. A file handler and my own console handler. Both of my handlers work fine. My logg

相关标签:
5条回答
  • 2020-11-27 12:18

    You must instruct your logger not to send its messages on up to its parent logger:

    ...
    import java.util.logging.*;
    ...
    Logger logger = Logger.getLogger(this.getClass().getName());
    logger.setUseParentHandlers(false);
    ...
    

    However, this should be done before adding any more handlers to logger.

    0 讨论(0)
  • 2020-11-27 12:20

    Just do

    LogManager.getLogManager().reset();
    
    0 讨论(0)
  • 2020-11-27 12:29

    Do a reset of the configuration and set the root level to OFF

    LogManager.getLogManager().reset();
    Logger globalLogger = Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
    globalLogger.setLevel(java.util.logging.Level.OFF);
    
    0 讨论(0)
  • 2020-11-27 12:36

    This is strange but Logger.getLogger("global") does not work in my setup (as well as Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)).

    However Logger.getLogger("") does the job well.

    Hope this info also helps somebody...

    0 讨论(0)
  • 2020-11-27 12:39

    The default console handler is attached to the root logger, which is a parent of all other loggers including yours. So I see two ways to solve your problem:

    If this is only affects this particular class of yours, the simplest solution would be to disable passing the logs up to the parent logger:

    logger.setUseParentHandlers(false);
    

    If you want to change this behaviour for your whole app, you could remove the default console handler from the root logger altogether before adding your own handlers:

    Logger globalLogger = Logger.getLogger("global");
    Handler[] handlers = globalLogger.getHandlers();
    for(Handler handler : handlers) {
        globalLogger.removeHandler(handler);
    }
    

    Note: if you want to use the same log handlers in other classes too, the best way is to move the log configuration into a config file in the long run.

    0 讨论(0)
提交回复
热议问题