23
I want to replace print statements with proper logging. How do I set it up?
Loading...
Q&A · Answered
I want to replace print statements with proper logging. How do I set it up?
Accepted answer
import logging
# Basic configuration
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('app.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Usage
logger.debug('Debug message')
logger.info('Info message')
logger.warning('Warning message')
logger.error('Error message')
logger.exception('Error with traceback')Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.