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)
raiseKey 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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
