Python / Core Python Fundamentals Interview Questions
Why should you use Python's logging module instead of print() in production code?
Using print() for diagnostics is fine during quick development, but it has serious limitations in any real-world application: output always goes to stdout, there is no severity level, you cannot turn it off without editing code, and there is no timestamp, file name, or line number.
Python's logging module solves all of these. It provides five severity levels in ascending order: DEBUG, INFO, WARNING, ERROR, CRITICAL. You set a threshold and only messages at or above that level are emitted.
import logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(name)s: %(message)s', handlers=[ logging.FileHandler('app.log'), logging.StreamHandler() # also print to console ] ) logger = logging.getLogger(__name__) # module-level logger def process_order(order_id): logger.debug('Processing order %s', order_id) try: result = fulfil(order_id) logger.info('Order %s fulfilled', order_id) return result except TimeoutError: logger.error('Timeout processing order %s', order_id, exc_info=True) raise
Key advantages over print: severity levels let you turn debug output off in production by raising the log level to WARNING. Named loggers (logging.getLogger(__name__)) let library authors log without polluting application output — consumers can configure whether to see library logs. exc_info=True automatically includes the traceback. Handlers route log records to files, external services, or email without touching the application logic.
More Related questions...