Notes about python logging

By | January 12, 2021

Consider the following code

import logging
logging.info('trying to log something')

Executing above:

  1. It won’t log anything to console, because it default to level warning
  2. 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:

  1. Running basicConfig(...) default adds the stream to stderr (unless specified explicitly) to root logger
  2. It sets the root logger level to INFO
  3. Log being sent to console by the root logger
  4. Calling basicConfig again is no-op because it’s already configured, in python 3.8 you can pass in force=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:

  1. It sets the level to the root logger
  2. The log instance inherited from the root logger
  3. 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:

  1. The log instance inherited from the root logger, notice basicConfig has not been called yet
  2. The root logger calls basicConfig
  3. 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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.