Python Logging - How to inherit root logger level & handler

后端 未结 1 1827
时光取名叫无心
时光取名叫无心 2021-01-01 23:20

I am a python newbie, trying to implement logging into my code. I have two modules

main.py submodule.py

main.py

相关标签:
1条回答
  • 2021-01-01 23:40

    The problem here is that you're not initializing the root logger; you're initializing the logger for your main module.

    Try this for main.py:

    import logging
    from logging.handlers import RotatingFileHandler
    import submodule
    
    logger = logging.getLogger()  # Gets the root logger
    logger.setLevel(logging.DEBUG)
    
    fh = RotatingFileHandler('master.log', maxBytes=2000000, backupCount=10)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    
    logger.debug('DEBUG LEVEL - MAIN MODULE')
    logger.info('INFO LEVEL - MAIN MODULE')
    
    submodule.loggerCall()
    

    Then try this for submodule.py:

    def loggerCall():
        logger = logging.getLogger(__name__)
        logger.debug('SUBMODULE: DEBUG LOGGING MODE : ')
        logger.info('Submodule: INFO LOG')
        return
    

    Since you said you wanted to send log messages from all your submodules to the same place, you should initialize the root logger and then simply use the message logging methods (along with setlevel() calls, as appropriate). Because there's no explicit handler for your submodule, logging.getLogger(__name__) will traverse the tree to the root, where it will find the handler you established in main.py.

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