python logging ensure a handler is added only once

前端 未结 5 827
时光取名叫无心
时光取名叫无心 2020-12-25 09:59

I have a piece of code that is initializing a logger as below.

logger = logging.getLogger()
hdlr = logging.FileHandler(\'logfile.log\')
formatter = logging.         


        
5条回答
  •  不思量自难忘°
    2020-12-25 10:31

    Well the logger.addHandler() will not add a handler if the handler already exists. To check if the handler is already there you can check the logger.handlers list:

    logger = logging.getLogger()
    hdlr = logging.FileHandler('logfile.log')
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr) 
    logger.setLevel(logging.DEBUG)
    print logger.handlers
    # []
    logger.addHandler(hdlr)
    print logger.handlers
    # []
    

    Beside that I will suggest putting this code in your main() function if you have one or in the __init__.py file of your package so to not have to call it each time. I will also suggest that you use a named logger, and do not use the root logger. Something like this:

    logger = logging.getLogger(__name__)
    ...
    

    Hope this was helpful :)

提交回复
热议问题