Intermediate LevelPython
How do you configure standard library logging with formatters, handlers, and hierarchical logger names instead of print()?
❓ Interview Prompt: Explain `logging` module, log levels (`DEBUG`, `INFO`, `WARNING`, `ERROR`), Handlers, Formatters, and hierarchical logger propagation.
Never use 'print()' for production applications! Python's built-in 'logging' module provides structured logging:
Architecture:
•
Loggers ('logging.getLogger(__name__)'): Hierarchical tree using dot notation ('app.service.user').
•
Handlers: Direct log outputs to 'StreamHandler' (stdout), 'FileHandler', or external syslog services.
•
Formatters: Define log output layout ('%(asctime)s [%(levelname)s] %(name)s: %(message)s').
Code Implementation Example
python
import logging
# Configure logger for current module
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info('Application started successfully')💡Configuring structured hierarchical logging with handlers and formatters.
🎯 Interview Key Takeaway
Use logging.getLogger(__name__) with structured formatters instead of print() statements in production.
#logging#Handlers#Formatters#Intermediate
Back to all Python Questions→