Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Magnus167/5e92089bdd25a49e4da39504dcb6e4fa to your computer and use it in GitHub Desktop.
Save Magnus167/5e92089bdd25a49e4da39504dcb6e4fa to your computer and use it in GitHub Desktop.
Explanation of the relationship between python logging root logger and other loggers

Explanation of the relationship between python logging root logger and other loggers

import logging
import submodule
# Note that by importing submodule here before we've setup the root logger, all uses of logger in submodule outside of
# functions will not use the loglevel we set here in main.py
logging.basicConfig()
logger = logging.getLogger()
# Note that nothing is passed to getLogger
# By passing nothing, logger is set to the "root" logger
# If we instead set logger to logging.getLogger(__name__) other modules will not inherit the settings from this module
logger.setLevel(logging.INFO)
logger.error('This will display')
logger.info('This will display')
logger.debug('This will not display')
submodule.func()
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
# Here in the submodule, set logger to a logger called __name__
# This will help identify that log messages generated here came from this submodule
# We don't set the loglevel with setLevel because that loglevel is inherited from the parent module that calls imports this
# submodule
logger.error('This will display')
logger.info('This will NOT display !!!') # This will not display because we import submodule in main.py before we've setup the
# root logger
logger.debug('This will not display')
def func():
logger.error('func : This will display')
logger.info('func : This will display') # This will display because though we import submodule in main.py before we setup
# the root logger, we don't call the submodule.func function until after the root logger is setup
logger.debug('func : This will not display')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment