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

Use a named logger per module.

pythonANYlogginglogger
python
import logging
logger = logging.getLogger(__name__)

Log to a file

Persist logs to disk for debugging after process exit.

pythonANYloggingfile
python
import logging

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

Include stack info in a log call

Attach the current stack to a log message.

pythonANYloggingstacktrace
python
logger.warning("Unexpected state", stack_info=True)

Attach exception info to logs

Log a message with traceback details.

pythonANYloggingexceptions
python
try:
    risky_call()
except Exception:
    logger.error("Failure", exc_info=True)

Warnings and Execution Traces

Force warnings to appear

Promote useful warnings during development.

pythonANYwarnings
python
import warnings
warnings.simplefilter('default')

Turn warnings into errors

Catch deprecated or risky behavior early.

bashANYwarningsstrictness
bash
python -W error app.py

Trace executed lines

Run a script and print executed lines.

bashANYtraceline-execution
bash
python -m trace --trace app.py

Count executed lines

Collect line execution counts for scripts.

bashANYtracecoverage-like
bash
python -m trace --count app.py

Signals and Crash Diagnostics

Dump traceback later with faulthandler

Emit stack traces after a timeout to catch hangs.

pythonANYfaulthandlerhangs
python
import faulthandler
import sys

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

Cancel delayed traceback dumping

Stop the scheduled faulthandler timeout.

pythonANYfaulthandler
python
faulthandler.cancel_dump_traceback_later()

Recommended next

No recommendations yet.