Search code examples
pythonloggingpython-logging

Python logging before you run logging.basicConfig?


It appears that if you invoke logging.info() BEFORE you run logging.basicConfig, the logging.basicConfig call doesn't have any effect. In fact, no logging occurs.

Where is this behavior documented? I don't really understand.


Solution

  • You can remove the default handlers and reconfigure logging like this:

    # if someone tried to log something before basicConfig is called, Python creates a default handler that
    # goes to the console and will ignore further basicConfig calls. Remove the handler if there is one.
    root = logging.getLogger()
    if root.handlers:
        for handler in root.handlers:
            root.removeHandler(handler)
    logging.basicConfig(format='%(asctime)s %(message)s',level=logging.DEBUG)