Python Tutorial / Read Tracebacks and Diagnose Problems with Debugging and Logging

Start debugging by reading the final exception and the relevant file and line in the traceback, then reproduce the input. A debugger reveals execution state, while logging records selected events at defined severity levels.

Reduce the failure to a reproducible case

Read the exception type and message at the bottom, then find your own code in the call chain. Before editing library internals, establish which inputs and settings reached them. A minimal reproduction reduces unrelated variables.

In VS Code, use a breakpoint to inspect variable values, the call stack and the next statement. Observing state before the failure often reveals more than repeatedly adding print statements after it.

For the relevant APIs and platform requirements, see Python: logging.

Exception propagation and automated failure checks build on the rules demonstrated in Handle Exceptions with try, except, else, finally and raise.

Run a calculation with logging

Save the complete code below as logging_demo.py in a separate practice folder, using UTF-8. Run python logging_demo.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.

import logging

logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(message)s")
logger = logging.getLogger(__name__)

def calculate(amounts):
    logger.debug("count=%s", len(amounts))
    if any(x < 0 for x in amounts):
        raise ValueError("negative amount")
    return sum(amounts)

try:
    total = calculate([3500, 8000, 2500])
except ValueError:
    logger.exception("calculation failed")
    raise SystemExit(1)
else:
    logger.info("total=%s", total)
print("finished")

Expected output:

finished

The output block shows standard output only. The log also contains INFO:total=14000, normally on standard error.

Choose levels and distinguish output channels

Level Typical role
DEBUG Detailed diagnostic information
INFO Normal progress or results
WARNING A condition requiring attention
ERROR An operation failed

Apply levels consistently within the application’s policy. INFO configuration hides the DEBUG count message. Tools combining standard output and standard error may show a different apparent ordering. File logging additionally requires decisions about location, rotation, retention and permissions.

Logging records a failure but does not automatically make the process fail. The revised handler records an unrecoverable ValueError and raises SystemExit(1), so the negative-input experiment does not print finished. Valid input logs INFO, prints finished and exits zero. Immediately afterward inspect $LASTEXITCODE in PowerShell or echo $? in a macOS/Ubuntu shell. Separately captured stdout and stderr can appear in a different observation order.

Official behavior and conditions: Python: sys.exit

Practice a deliberate failure and retain useful context

  1. Replace one amount with -1 and inspect the failure log and traceback.
  2. Switch to DEBUG and verify that count=3 is recorded.
  3. Restore the data and level, then verify the normal result again.

Do not hide the failure with an empty broad handler. Record the relevant operation and propagate a failure when the caller needs to react. Avoid passwords, authentication headers and full personal-data records in logs. Repeatedly logging large objects also consumes time and storage.

User guidance and developer diagnostics serve different readers. The automated test lesson turns a reproducible case into a repeatable check once the expected behavior is clear.