Skip to main content

Beautiful, readable Python tracebacks with colors and formatting

Project description

Beautiful, Readable Python Stack Traces

Release Notes Downloads Python Versions GitHub CI Status License: MIT

Human readable stacktraces for Python.

Comparison of standard Python traceback vs Beautiful Traceback

[!NOTE] This is a fork of the pretty-traceback repo with simplified development and improvements for better integration with FastAPI, structlog, IPython, pytest, and more. This project is used in python-starter-template to provide better debugging experience in production environments.

Quick Start

The fastest way to see it in action:

# Clone and run an example
git clone https://github.com/iloveitaly/beautiful-traceback
cd beautiful-traceback
uv run examples/simple.py

Overview

Beautiful Traceback groups together what belongs together, adds coloring and alignment. All of this makes it easier for you to see patterns and filter out the signal from the noise. This tabular format is best viewed in a wide terminal.

Installation

From PyPI (when published)

# Using uv (recommended)
uv add beautiful-traceback

# Using pip
pip install beautiful-traceback

Development Installation

To install from source:

git clone https://github.com/iloveitaly/beautiful-traceback
cd beautiful-traceback
uv sync

Run examples:

uv run examples/simple.py

Run tests:

uv run pytest

Usage

Add the following to your __main__.py or the equivalent module which is your entry point.

try:
    import beautiful_traceback
    beautiful_traceback.install()
except ImportError:
    pass    # no need to fail because of missing dev dependency

Please do not add this code e.g. to your __init__.py or any other module that your users may import. They may not want you to mess with how their tracebacks are printed.

If you do feel the overwhelming desire to import the beautiful_traceback in code that others might import, consider using the envvar argument, which will cause the install function to effectively be a noop unless you set ENABLE_BEAUTIFUL_TRACEBACK=1.

try:
    import beautiful_traceback
    beautiful_traceback.install(envvar='ENABLE_BEAUTIFUL_TRACEBACK')
except ImportError:
    pass    # no need to fail because of missing dev dependency

Note, that the hook is only installed if the existing hook is the default. Any existing hooks that were installed before the call of beautiful_traceback.install will be left in place.

LoggingFormatter

A logging.Formatter subclass is also available (e.g. for integration with Flask, FastAPI, etc).

import os
from flask.logging import default_handler

try:
    if os.getenv('FLASK_DEBUG') == "1":
        import beautiful_traceback
        default_handler.setFormatter(beautiful_traceback.LoggingFormatter())
except ImportError:
    pass    # no need to fail because of missing dev dependency

IPython and Jupyter Integration

Beautiful Traceback works seamlessly in IPython and Jupyter notebooks:

# Load the extension
%load_ext beautiful_traceback

# Unload if needed
%unload_ext beautiful_traceback

The extension automatically installs beautiful tracebacks for your interactive session.

Pytest Integration

Beautiful Traceback includes a pytest plugin that automatically enhances test failure output.

Automatic Activation

The plugin activates automatically when beautiful-traceback is installed. No configuration needed!

Configuration Options

Customize the plugin in your pytest.ini or pyproject.toml:

[tool.pytest.ini_options]
enable_beautiful_traceback = true                    # Enable/disable the plugin
enable_beautiful_traceback_local_stack_only = true   # Show only local code (filter libraries)
beautiful_traceback_exclude_patterns = [             # Regex patterns to drop frames
  "click/core\\.py",
]

Or in pytest.ini:

[pytest]
enable_beautiful_traceback = true
enable_beautiful_traceback_local_stack_only = true
beautiful_traceback_exclude_patterns =
    click/core\.py

Example: filter out pytest, pluggy, and playwright frames from CI tracebacks:

[tool.pytest.ini_options]
beautiful_traceback_exclude_patterns = [
  "^_pytest/",
  "^pluggy/",
  "^playwright/",
]

Pattern Matching: Patterns are tested against multiple representations of each frame:

  • _pytest/runner.py (short module path)
  • /path/to/site-packages/_pytest/runner.py (full module path)
  • <site> _pytest/runner.py:353 from_call result: ... (formatted line with short path)
  • <site> /path/to/.../runner.py:353 from_call result: ... (formatted line with full path)

This allows you to write simpler patterns like ^_pytest/ instead of needing to match the full site-packages path.

Threading Support

beautiful_traceback.install() hooks both sys.excepthook and threading.excepthook, so unhandled exceptions in background threads are automatically formatted. Thread name and daemon status are shown in the exception header (e.g., Exception in thread Worker-1 (daemon):). The exc_to_json() function also accepts an optional thread parameter to include thread metadata in structured JSON output. See examples/threading_example.py for a complete demonstration.

Examples

Check out the examples/ directory for detailed usage examples including basic usage, exception chaining, logging integration, and more.

# Quick single-exception example
uv run examples/simple.py

# Interactive demo with multiple exception types
uv run examples/demo.py

Configuration

Installation Options

Beautiful Traceback supports several configuration options:

beautiful_traceback.install(
    color=True,                            # Enable colored output
    only_tty=True,                         # Only activate for TTY output
    only_hook_if_default_excepthook=True,  # Only install if default hook
    local_stack_only=False,                # Filter to show only local code
    exclude_patterns=["click/core\\.py"],  # Regex patterns to drop frames
    envvar='ENABLE_BEAUTIFUL_TRACEBACK'    # Optional environment variable gate
)

Environment Variables

  • NO_COLOR - Disables colored output when set (respects no-color.org standard)
  • ENABLE_BEAUTIFUL_TRACEBACK - Controls activation when using the envvar parameter (set to 1 to enable)

LoggingFormatterMixin

For more advanced logging integration, you can use LoggingFormatterMixin as a base class:

import logging
import beautiful_traceback

class MyFormatter(beautiful_traceback.LoggingFormatterMixin, logging.Formatter):
    def __init__(self):
        super().__init__(fmt='%(levelname)s: %(message)s')

This gives you full control over the log format while adding beautiful traceback support.

Global Installation via PTH File

You can enable beautiful-traceback across all Python projects without modifying any source code by using a .pth file. Python automatically executes import statements in .pth files during interpreter startup, making this perfect for development environments.

Using the CLI Command

The easiest way to inject beautiful-traceback into your current virtual environment:

beautiful-traceback

This command:

  • Only works within virtual environments (for safety)
  • Installs the .pth file into your current environment's site-packages
  • Displays the installation path every time it runs

Output:

Beautiful traceback injection installed: /path/to/.venv/lib/python3.11/site-packages/beautiful_traceback_injection.pth

Using a Shell Function (Alternative)

Alternatively, add this function to your .zshrc or .bashrc:

# Create a file to automatically import beautiful-traceback on startup
python-inject-beautiful-traceback() {
  local site_packages=$(python -c "import site; print(site.getsitepackages()[0])")

  local pth_file=$site_packages/beautiful_traceback_injection.pth
  local py_file=$site_packages/_beautiful_traceback_injection.py

  cat <<'EOF' >"$py_file"
def run_startup_script():
  try:
    import beautiful_traceback
    beautiful_traceback.install(only_tty=False)
  except ImportError:
    pass

run_startup_script()
EOF

  echo "import _beautiful_traceback_injection" >"$pth_file"
  echo "Beautiful traceback injection created: $pth_file"
}

After sourcing your shell config, run python-inject-beautiful-traceback to enable beautiful tracebacks globally for that Python environment.

Alternatives

Beautiful Traceback is heavily inspired by the backtrace module by nir0s but there are many others (sorted by github stars):

License

MIT License


This project was created from iloveitaly/python-package-template

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

beautiful_traceback-0.6.0.tar.gz (15.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

beautiful_traceback-0.6.0-py3-none-any.whl (20.2 kB view details)

Uploaded Python 3

File details

Details for the file beautiful_traceback-0.6.0.tar.gz.

File metadata

  • Download URL: beautiful_traceback-0.6.0.tar.gz
  • Upload date:
  • Size: 15.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for beautiful_traceback-0.6.0.tar.gz
Algorithm Hash digest
SHA256 9e17fcbf3dd5e31dd06daa745ab4b4197220d1880a848b7dcae31b33e06a6908
MD5 ef62c512a57a8d7e29c18bdace859746
BLAKE2b-256 cb585aecf7e9b1527742edd8460e69ca6fe8d66477ba7c85a523971da8c08401

See more details on using hashes here.

File details

Details for the file beautiful_traceback-0.6.0-py3-none-any.whl.

File metadata

  • Download URL: beautiful_traceback-0.6.0-py3-none-any.whl
  • Upload date:
  • Size: 20.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for beautiful_traceback-0.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f90bcd36dc7546f4b5e5e940b9f8e611f8a7626167daccb611a8611c3aa6dfef
MD5 03ad6fc529e9998388d82691105c5423
BLAKE2b-256 07146ad4f7301cbc564e833a182e61848a5e3b0dcccce33a7cc75382bf3ce1f2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page