Skip to main content
  1. Posts/

The Complete Guide to Logging in Python

··235 words·2 mins·

📋 Still using print() to debug in Python? It’s time to upgrade.

print() statements work during development, but in production they’re a trap: no levels, no source tracking, and no automatic persistence. Python’s logging module is the right solution.

📊 The 5 log levels and when to use them:

LevelUsage
DEBUGTechnical details during development (variables, iterations)
INFONormal operations (server start, successful transaction)
WARNINGSomething unexpected but handled (low disk space, deprecated API)
ERRORSomething failed but the app continues (DB query failed)
CRITICALSerious failure, possible system crash

🔧 Basic example:

import logging
logger = logging.getLogger('my_app')
logger.setLevel(logging.DEBUG)

# Console handler (INFO+) and file handler (DEBUG+)
console_handler = logging.StreamHandler()
file_handler = logging.FileHandler('app.log')
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

⚠️ The most common mistake when logging exceptions:

# BAD: only captures the error message
logger.error(f'Error: {e}')

# GOOD: captures the full stack trace
logger.error(f'Error processing user {user_id}', exc_info=True)

🔍 Explanation in a nutshell

A “stack trace” is the history of function calls that led to the error — basically the crime scene map. With exc_info=True, the log includes exactly which line failed and why, without needing to reproduce the error locally.

More information at the link 👇

Also published on LinkedIn.
Juan Pedro Bretti Mandarano
Author
Juan Pedro Bretti Mandarano