Skip to content

Q&A · Answered

How to use Python logging module properly

asked 9 months, 1 week ago 653 views 1 answer
23

I want to replace print statements with proper logging. How do I set it up?

1 Answer

One accepted
6

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
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')

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.