gotchapythonModerate
logging.basicConfig() only works on first call
Viewed 0 times
force= parameter requires Python 3.8+
logging basicConfiglogging not workinglog configurationgetLoggerforce basicConfig
Problem
Calling logging.basicConfig() multiple times has no effect after the first call. Imported libraries may call it before your code runs, causing your configuration to be silently ignored.
Solution
Use logging.getLogger() and configure handlers explicitly:
import logging
# Don't rely on basicConfig in libraries
logger = logging.getLogger(__name__)
# Explicit handler configuration (always works)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
# Or force basicConfig to reconfigure
logging.basicConfig(level=logging.DEBUG, force=True) # Python 3.8+
import logging
# Don't rely on basicConfig in libraries
logger = logging.getLogger(__name__)
# Explicit handler configuration (always works)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
# Or force basicConfig to reconfigure
logging.basicConfig(level=logging.DEBUG, force=True) # Python 3.8+
Why
basicConfig() checks if the root logger already has handlers. If any handler exists (from a library import or previous call), it does nothing. This is a common source of 'why aren't my logs showing?' bugs.
Gotchas
- force=True parameter was added in Python 3.8
- Libraries should use getLogger(__name__) and never call basicConfig
- The root logger propagates to all child loggers by default
Code Snippets
Reliable logging configuration
import logging
# UNRELIABLE (may be ignored):
logging.basicConfig(level=logging.DEBUG)
# RELIABLE:
logging.basicConfig(level=logging.DEBUG, force=True) # 3.8+
# MOST RELIABLE:
logger = logging.getLogger('myapp')
logger.setLevel(logging.DEBUG)
if not logger.handlers:
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
logger.addHandler(handler)Context
When configuring Python logging, especially in applications that import third-party libraries
Revisions (0)
No revisions yet.