Debug-friendly stack traces, with variable values and semantic highlighting

0.2.12 · active · verified Wed Apr 15

Stackprinter is a Python library that provides enhanced, debug-friendly stack traces. It displays more code context, current variable values, and uses semantic highlighting to make tracebacks more readable. The library is actively maintained, with a current version of 0.2.12, and receives updates periodically to support newer Python versions and address issues.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates two ways to use stackprinter: integrating with Python's standard logging module for automatic verbose exception logging, and manually calling `stackprinter.show()` within an `except` block for immediate, enhanced traceback output. The `set_excepthook()` method (commented out) is also available to globally replace Python's default exception printout.

import stackprinter
import logging
import sys

# Option 1: Replace the default excepthook for all uncaught exceptions
# stackprinter.set_excepthook(style='darkbg')

# Option 2: Use in a try-except block or integrate with logging

class VerboseExceptionFormatter(logging.Formatter):
    def formatException(self, exc_info):
        # exc_info is a tuple (type, value, traceback)
        msg = stackprinter.format(exc_info, style='darkbg', source_lines=7, truncate_vals=200)
        return msg

def configure_logger(logger_name=None):
    formatter = VerboseExceptionFormatter('%(asctime)s %(levelname)s: %(message)s')
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(formatter)
    logger = logging.getLogger(logger_name)
    logger.addHandler(handler)
    logger.setLevel(logging.ERROR)
    return logger

logger = configure_logger('my_app')

def problematic_function(a, b):
    result = a / b
    return result

def main():
    x = 10
    y = 0
    try:
        problematic_function(x, y)
    except ZeroDivisionError:
        logger.exception('An error occurred during calculation:')
    except TypeError as e:
        # For manual formatting and printing
        print('\n--- Manual stackprinter output ---\n')
        stackprinter.show(e, style='darkbg')

if __name__ == '__main__':
    main()

view raw JSON →