MermaidTrace: Visualize Your Python Code Logic
Stop drowning in cryptic logs. One line of code to transform complex execution logic into clear Mermaid sequence diagrams.
🏗️ Architecture
flowchart TB
%% Style Definitions
classDef userLayer fill:#e3f2fd,stroke:#1565c0,stroke-width:2px,color:#0d47a1,rx:5,ry:5
classDef coreLayer fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#bf360c,rx:5,ry:5
classDef ioLayer fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#1b5e20,rx:5,ry:5
classDef vizLayer fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#4a148c,rx:5,ry:5
classDef storage fill:#eceff1,stroke:#455a64,stroke-width:2px,color:#263238,shape:cyl
subgraph User["👤 User Integration"]
direction TB
Decorator["@trace / @trace_class"]:::userLayer
Middleware["FastAPI Middleware"]:::userLayer
Callback["LangChain Callback"]:::userLayer
end
subgraph Core["⚙️ Core Engine"]
direction TB
Context["ContextVars<br/>(Trace Context)"]:::coreLayer
EventBus["Event Bus<br/>(LogContext)"]:::coreLayer
Masker["Data Masking<br/>(Sanitizer)"]:::coreLayer
end
subgraph IO["⚡ Async I/O Layer"]
direction TB
Queue["Async Queue<br/>(Non-blocking)"]:::ioLayer
Writer["File Handler<br/>(Rotating/Timed)"]:::ioLayer
end
Storage[(".mmd File")]:::storage
subgraph Viz["🌐 Visualization"]
direction TB
Watcher["Watchdog<br/>(File Monitor)"]:::vizLayer
Server["FastAPI Server<br/>(SSE Support)"]:::vizLayer
Browser["Web Browser<br/>(Mermaid.js + PanZoom)"]:::vizLayer
end
%% Data Flow
Decorator --> Context
Middleware --> Context
Callback --> Context
Context --> EventBus
EventBus --> Masker
Masker --> Queue
Queue --> Writer
Writer --> Storage
Storage -.-> Watcher
Watcher --> Server
Server == "SSE Push" ==> Browser
%% Link Styles
linkStyle default stroke:#607d8b,stroke-width:2px
⚡️ 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
(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:
🎯 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
@traceor@trace_interactionto functions. - Auto-Instrumentation: Use
@trace_classto 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_objectto trace calls inside external libraries. - Async Support: Seamlessly works with
asynciocoroutines 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
Metadata
Release files for mermaid-trace 0.7.1.post0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| mermaid_trace-0.7.1.post0.tar.gz | 2.2 MB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| mermaid_trace-0.7.1.post0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 3.4 MB
Release files / mermaid_trace-0.7.1.post0.tar.gz
| Download URL | mermaid_trace-0.7.1.post0.tar.gz |
|---|---|
| Size | 2.2 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
87b1afbc6dc480629d29b86001d2a90755c3aa58f30fadb75f5353963046ddb9
|
|
BLAKE2b-256 checksum How to use checksums |
0ef9d75416a2f65f0cc30d17fba71f0cab79e30dfb3088e1eab26abe68537dfd
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Mar 6, 2026.
Transparency logRelease files / mermaid_trace-0.7.1.post0-py3-none-any.whl
| Download URL | mermaid_trace-0.7.1.post0-py3-none-any.whl |
|---|---|
| Size | 1.2 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2976b0eaee5023d307c6da6b962a0436d1e9956a984c35c537c077811d81951b
|
|
BLAKE2b-256 checksum How to use checksums |
8cacb1fb9d1ec20a4072e26db711ebe6706b6c86b54d2ea68c21af6a60293185
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Mar 6, 2026.
Transparency log