Skip to main content

Visualize your Python code execution flow as Mermaid Sequence Diagrams.

Project description

MermaidTrace: Visualize Your Python Code Logic

MermaidTrace Logo

Stop drowning in cryptic logs. One line of code to transform complex execution logic into clear Mermaid sequence diagrams.

🌐 Language: English | 中文

CSDN Blog GitHub Gitee

PyPI version PyPI Downloads Python Versions License CI Status Ruff Mypy

🏗️ Architecture

flowchart TB
    subgraph User["👤 User Code"]
        A["@trace decorator"]
        B["@trace_class"]
        C["patch_object()"]
    end

    subgraph Core["⚙️ Core Layer"]
        D["Decorators"]
        E["LogContext"]
        F["FlowEvent"]
        G["MermaidFormatter"]
        H["MermaidConfig"]
    end

    subgraph Handlers["📦 Handlers"]
        I["MermaidFileHandler"]
        J["AsyncMermaidHandler"]
        K["RotatingHandler"]
    end

    subgraph Output["📄 Output"]
        L[("flow.mmd")]
        M["🌐 Live Preview"]
    end

    subgraph Integrations["🔗 Integrations"]
        N["FastAPI Middleware"]
        O["LangChain Callback"]
    end

    A --> D
    B --> D
    C --> D
    D --> E
    D --> F
    E --> F
    F --> G
    H -.-> D
    G --> I
    G --> J
    G --> K
    I --> L
    J --> L
    K --> L
    L --> M
    N --> D
    O --> D

    style User fill:#e1f5fe,stroke:#01579b
    style Core fill:#fff3e0,stroke:#e65100
    style Handlers fill:#e8f5e9,stroke:#1b5e20
    style Output fill:#fce4ec,stroke:#880e4f
    style Integrations fill:#f3e5f5,stroke:#4a148c

⚡️ Understand MermaidTrace in 5 Seconds

1. Original Code (15+ lines)

@trace(source="User", target="OrderSys")
def create_order(user_id, items):
    # Complex business logic
    if not check_inventory(items):
        return "Out of Stock"

    # Nested logic calls
    price = calculate_price(items)
    discount = get_discount(user_id)
    final = price - discount

    # External service interactions
    res = pay_service.process(final)
    if res.success:
        update_stock(items)
        send_notif(user_id)
        return "Success"
    return "Failed"

2. Auto-Generated Sequence Diagram

sequenceDiagram
    autonumber
    User->>OrderSys: create_order(user_id, items)
    activate OrderSys
    OrderSys->>Inventory: check_inventory(items)
    Inventory-->>OrderSys: True
    OrderSys->>Pricing: calculate_price(items)
    Pricing-->>OrderSys: 100.0
    OrderSys->>UserDB: get_discount(user_id)
    UserDB-->>OrderSys: 5.0
    OrderSys->>PayService: process(95.0)
    activate PayService
    PayService-->>OrderSys: success
    deactivate PayService
    OrderSys->>Inventory: update_stock(items)
    OrderSys->>Notification: send_notif(user_id)
    OrderSys-->>User: "Success"
    deactivate OrderSys

🚀 Dynamic Demo & Online Tryout

🎬 Quick Demo

MermaidTrace Master Preview

(Master Preview: Multi-file browsing, live-reload, and interactive pan/zoom)

sequenceDiagram
    participant CLI as mermaid-trace CLI
    participant App as Python App
    participant Web as Live Preview

    Note over CLI, Web: Enable Live Preview Mode
    CLI->>Web: Start HTTP Server (localhost:8000)
    App->>App: Run Logic (with @trace decorator)
    App->>App: Auto-update flow.mmd
    Web->>Web: File Change Detected (Hot Reload)
    Web-->>CLI: Render Latest Diagram

(From adding decorators to browser live preview in 10 seconds)

🛠️ Try Online (Google Colab)

No local setup required. Experience core features in your browser:

Open In Colab


🎯 Why MermaidTrace? (Use Cases)

1. Master "Legacy" Codebases

Pain: Taking over a complex, undocumented legacy project with tangled function calls. Solution: Add @trace_class or @trace to entry points and run the code once. Value: Instantly generate a complete execution path map to understand the architecture.

2. Automated Technical Docs

Pain: Manual sequence diagrams are time-consuming and quickly become outdated. Solution: Integrate MermaidTrace during development. Value: Diagrams stay 100% in sync with your code logic automatically.

3. Debug Complex Recursion & Concurrency

Pain: Nested calls or async tasks produce interleaved logs that are impossible to read. Solution: Use built-in async support and intelligent collapsing. Value: Visualize recursion depth and concurrency flow to pinpoint logic bottlenecks.


🚀 Quick Start in 3 Steps

1. Install

pip install mermaid-trace

2. Add Decorators

from mermaid_trace import trace, configure_flow

# Configure output file
configure_flow("my_flow.mmd")

@trace(source="User", target="AuthService")
def login(username):
    return verify_db(username)

@trace(source="AuthService", target="DB")
def verify_db(username):
    return True

login("admin")

3. View Diagram

Run the built-in CLI tool to preview in real-time (with hot-reload):

# Preview a single file (Auto-reload, Pan/Zoom supported)
mermaid-trace serve my_flow.mmd

# Preview a directory (File browser, Multi-file switching)
mermaid-trace serve .

🔗 LangChain Integration

Visualize LLM chains, agents, and RAG retrieval with a single handler:

from mermaid_trace.integrations.langchain import MermaidTraceCallbackHandler

handler = MermaidTraceCallbackHandler(host_name="MyAIApp")
# Pass to any LangChain object
chain.invoke({"input": "..."}, config={"callbacks": [handler]})

✨ Key Features

  • Decorator-Driven: Simply add @trace or @trace_interaction to functions.
  • Auto-Instrumentation: Use @trace_class to trace a whole class at once.
  • Data Privacy: Automatic Data Masking for sensitive fields (passwords, tokens).
  • Performance Control: Configurable Sampling Rate for high-throughput systems.
  • Distributed Tracing: Support for W3C Trace Context, B3, and custom headers to link microservices.
  • Third-Party Patching: Use patch_object to trace calls inside external libraries.
  • Async Support: Seamlessly works with asyncio coroutines and concurrency.
  • Enhanced Web UI: Interactive preview server with file browsing, auto-reload, and pan/zoom support.
  • Intelligent Collapsing: Automatically collapses repetitive calls and identifies loops.
  • FastAPI Integration: Middleware for zero-config HTTP request tracing with header propagation.
  • LangChain Integration: Callback Handler for LLM chains and agent visualization.
  • Detailed Exceptions: Captures full stack traces for errors, displayed in the diagram.

📚 Documentation

Core Documentation

User Guide · API Reference · Contributing Guidelines · Changelog · License

Code Comment Documents

Category Links
Core Modules Context · Decorators · Events · Formatter
Handlers Async Handler · Mermaid Handler
Integrations FastAPI
Others init · CLI

🤝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for details.


📄 License

MIT

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

mermaid_trace-0.7.0.post0.tar.gz (1.0 MB view details)

Uploaded Source

Built Distribution

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

mermaid_trace-0.7.0.post0-py3-none-any.whl (50.1 kB view details)

Uploaded Python 3

File details

Details for the file mermaid_trace-0.7.0.post0.tar.gz.

File metadata

  • Download URL: mermaid_trace-0.7.0.post0.tar.gz
  • Upload date:
  • Size: 1.0 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for mermaid_trace-0.7.0.post0.tar.gz
Algorithm Hash digest
SHA256 b3f621c6a9d60f0e16ffbf2b25c873ee580106a0c747f317df2553ec9a011817
MD5 1fa4400a6a4fb7e8e2ec9dc5bd5ec525
BLAKE2b-256 ced82cb6beb7404fbea027aff567689fc54a3982c554d676c01f2b8bc3481b3a

See more details on using hashes here.

Provenance

The following attestation bundles were made for mermaid_trace-0.7.0.post0.tar.gz:

Publisher: release.yml on xt765/mermaid-trace

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file mermaid_trace-0.7.0.post0-py3-none-any.whl.

File metadata

File hashes

Hashes for mermaid_trace-0.7.0.post0-py3-none-any.whl
Algorithm Hash digest
SHA256 7dc97f520a06f1fa20e1596be42e3a403426769590f26a8963a7ea63d305e66c
MD5 20f4bc062e13ad02463a150426fe52ee
BLAKE2b-256 a996d3eb7adebc2b3045b3ab807d573cf7e95d923556e8793cf8721e4c805aac

See more details on using hashes here.

Provenance

The following attestation bundles were made for mermaid_trace-0.7.0.post0-py3-none-any.whl:

Publisher: release.yml on xt765/mermaid-trace

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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