Removing handlers from python's logging loggers

后端 未结 4 1897
礼貌的吻别
礼貌的吻别 2020-12-13 23:03

I am playing with Python\'s logging system. I have noticed a strange behavior while removing handlers from a Logger object in a loop. Namely, my for loop removes all but one

相关标签:
4条回答
  • 2020-12-13 23:36

    If you don't want to delete them all (thanks for the tip @CatPlusPlus):

    testLogger.handlers = [
        h for h in testLogger.handlers if not isinstance(h, logging.StreamHandler)]
    
    0 讨论(0)
  • 2020-12-13 23:37

    This isn't logger-specific behaviour. Never mutate (insert/remove elements) the list you're currently iterating on. If you need, make a copy. In this case testLogger.handlers = [] should do the trick.

    0 讨论(0)
  • 2020-12-13 23:40

    instead of mutating undocumented .handler:

    Option 1

    logging.getLogger().removeHandler(logging.getLogger().handlers[0])
    

    this way you remove exactly the preexisting handler object via offical api. Or to remove all handlers:

    logger = logging.getLogger()
    while logger.hasHandlers():
        logger.removeHandler(logger.handlers[0])
    

    Option 2

    logging.config.dictConfig(config={'level': logging.DEBUG, 'handlers': []}
    

    Not only removes but prevents its creation. List root will have [] handlers

    0 讨论(0)
  • 2020-12-13 23:55

    I've just found out that you can also do that within a logging .ini file, with the following block:

    [logger_stpipe]
    handlers=
    propagate=1
    qualname=stpipe
    

    It basically deactivates all handlers for a given logger. But it's somewhat limited because you have to know the Logger's name in advance.

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