Python Logging and Tracing Cheat Sheet

Reference for Python logging, stack traces, warning visibility, trace hooks, and instrumentation patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Logging Core Patterns
Create a module logger
import logging
logger = logging.getLogger(__name__)

# Use a named logger per module.

Log to a file
import logging

logging.basicConfig(filename='app.log', level=logging.DEBUG)

# Persist logs to disk for debugging after process exit.

Include stack info in a log call
logger.warning("Unexpected state", stack_info=True)

# Attach the current stack to a log message.

Attach exception info to logs
try:
    risky_call()
except Exception:
    logger.error("Failure", exc_info=True)

# Log a message with traceback details.

## Warnings and Execution Traces
Force warnings to appear
import warnings
warnings.simplefilter('default')

# Promote useful warnings during development.

Turn warnings into errors
python -W error app.py

# Catch deprecated or risky behavior early.

Trace executed lines
python -m trace --trace app.py

# Run a script and print executed lines.

Count executed lines
python -m trace --count app.py

# Collect line execution counts for scripts.

## Signals and Crash Diagnostics
Dump traceback later with faulthandler
import faulthandler
import sys

faulthandler.dump_traceback_later(30, repeat=True, file=sys.stderr)

# Emit stack traces after a timeout to catch hangs.

Cancel delayed traceback dumping
faulthandler.cancel_dump_traceback_later()

# Stop the scheduled faulthandler timeout.

Recommended next

No recommendations yet.