Consider the following code
import logging
logging.info('trying to log something')
Executing above:
- It won’t log anything to console, because it default to level
warning
- It won’t log anything to console, because no stream has been set
import logging
logging.basicConfig(level=logging.INFO)
logging.info('trying to log something')
logging.basicConfig(level=logging.DEBUG)
logging.debug('trying to log something debug')
Executing above:
- Running
basicConfig(...)
default adds the stream tostderr
(unless specified explicitly) to root logger - It sets the root logger level to
INFO
- Log being sent to console by the root logger
- Calling
basicConfig
again is no-op because it’s already configured, in python 3.8 you can pass inforce=True
to override the config.
You can set the stream in basicConfig like logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
log.info('trying to log by log instance')
Executing above:
- It sets the level to the root logger
- The log instance inherited from the root logger
- We can see the logs sent to console by the log instance
import logging
log = logging.getLogger(__name__)
log.info('trying to log by log instance')
logging.basicConfig(level=logging.INFO)
logging.info('trying to log by root logger')
Executing above:
- The log instance inherited from the root logger, notice
basicConfig
has not been called yet - The root logger calls
basicConfig
- Only the log from root logger being sent to console
Ensure events are not logged before the logging system has been configured. Usually this means avoiding log events or doing any work at the global (module level) scope.
https://stackoverflow.com/questions/65676510/calling-logging-interferes-other-modules