Forked from gene1wood/01-explanation-of-python-logging-and-the-root-logger.md
Created
October 24, 2022 15:50
-
-
Save Magnus167/5e92089bdd25a49e4da39504dcb6e4fa to your computer and use it in GitHub Desktop.
Explanation of the relationship between python logging root logger and other loggers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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