Interview question
What is the difference between logging and using print() for debugging? Debugging के लिए logging और print() में क्या अंतर है?
Answer
| Aspect | print() | logging |
|---|---|---|
| Severity levels | No distinction | DEBUG, INFO, WARNING, ERROR, CRITICAL |
| Output control | Always prints to stdout | Configurable destinations (file, console, remote) |
| Production use | Must be manually removed | Can be turned on/off via level configuration |
| Includes context | Manual only | Automatic timestamps, module names, line numbers |
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
logger.debug('Detailed diagnostic info') # for development only
logger.info('General informational message') # normal operation events
logger.warning('Something unexpected') # potential issue
logger.error('An error occurred') # error that was handled
logger.critical('Critical failure') # severe error, app may not continue
# Setting level to WARNING hides debug/info without removing the log calls
logging.getLogger().setLevel(logging.WARNING)
logger.debug('This will NOT be shown now')
logger.warning('This WILL be shown')
# Logging exceptions with full traceback
try:
1 / 0
except ZeroDivisionError:
logger.exception('Division failed') # includes traceback automatically
# Why print() is problematic for production debugging:
# - can't easily filter by severity
# - clutters stdout, mixed with actual program output
# - no timestamps or context by default
# - must be manually found and removed before shipping| पहलू | print() | logging |
|---|---|---|
| Severity levels | कोई अंतर नहीं | DEBUG, INFO, WARNING, ERROR, CRITICAL |
| Output control | हमेशा stdout पर | Configurable destinations |
| Production use | Manually हटाना पड़ता है | Level configuration से on/off |
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
logger.debug('Detailed diagnostic info')
logger.info('General info message')
logger.warning('कुछ अनपेक्षित')
logger.error('Error हुआ')
logger.critical('Critical failure')
# Level को WARNING set करने से debug/info छुप जाते हैं
logging.getLogger().setLevel(logging.WARNING)
logger.debug('अब यह नहीं दिखेगा')
logger.warning('यह दिखेगा')
# Exception log करना with traceback
try:
1 / 0
except ZeroDivisionError:
logger.exception('Division fail हुआ')Was this answer clear?