Visualize your Python code execution flow as Mermaid Sequence Diagrams.
Project description
MermaidTrace: The Python Logger That Draws Diagrams
📋 Overview
Stop reading logs. Start watching them.
MermaidTrace is a specialized logging tool that automatically generates Mermaid JS sequence diagrams from your code execution. It's perfect for visualizing complex business logic, microservice interactions, or asynchronous flows.
📚 Documentation
Core Documentation
User Guide · API Reference · Contributing Guidelines · Changelog · License
Code Comment Documents (Chinese)
| Category | Links |
|---|---|
| Core Modules | Context · Decorators · Events · Formatter |
| Handlers | Async Handler · Mermaid Handler |
| Integrations | FastAPI |
| Others | init · CLI |
✨ Key Features
- Decorator-Driven: Just add
@traceor@trace_interactionto your functions. - Auto-Instrumentation: Use
@trace_classto trace a whole class at once. - Third-Party Patching: Use
patch_objectto trace calls inside external libraries. - Auto-Diagramming: Generates
.mmdfiles that can be viewed in VS Code, GitHub, or Mermaid Live Editor. - Async Support: Works seamlessly with
asynciocoroutines. - Context Inference: Automatically tracks nested calls and infers
sourceparticipants usingcontextvars. - Intelligent Collapsing: Prevents diagram explosion by collapsing repetitive high-frequency calls and identifying recurring patterns (e.g., loops).
- Detailed Exceptions: Captures full stack traces for errors, displayed in interactive notes.
- Simplified Objects: Automatically cleans up memory addresses (e.g.,
<__main__.Obj at 0x...>-><Obj>) and groups consecutive identical items in lists/tuples (e.g.,[<Obj> x 5]) for cleaner diagrams. - Log Rotation: Supports
RotatingMermaidFileHandlerfor handling long-running systems by splitting logs based on size or time. - FastAPI Integration: Includes middleware for zero-config HTTP request tracing, supporting distributed tracing via
X-Trace-IDandX-Sourceheaders. - CLI Tool: Built-in viewer with live-reload to preview diagrams in your browser.
🚀 Quick Start
Installation
pip install mermaid-trace
Basic Usage
from mermaid_trace import trace, configure_flow
import time
# 1. Configure output
# Recommendation: Store diagrams in a dedicated directory (e.g., mermaid_diagrams/)
configure_flow("mermaid_diagrams/my_flow.mmd", async_mode=True)
# 2. Add decorators
@trace(source="Client", target="PaymentService", action="Process Payment")
def process_payment(amount):
if check_balance(amount):
return "Success"
return "Failed"
@trace(source="PaymentService", target="Database", action="Check Balance")
def check_balance(amount):
return True
# 3. Run your code
process_payment(100)
Configuration
You can configure global settings via configure_flow or environment variables to control performance and behavior.
configure_flow(
"flow.mmd",
overwrite=True, # Overwrite the file on each restart (default: True)
level=logging.DEBUG,
queue_size=5000, # Increase buffer for high-throughput
config_overrides={
"capture_args": False, # Disable arg capturing for max performance
"max_string_length": 100 # Increase string truncation limit
}
)
Environment Variables:
MERMAID_TRACE_CAPTURE_ARGS(true/false)MERMAID_TRACE_MAX_STRING_LENGTH(int)MERMAID_TRACE_MAX_ARG_DEPTH(int)MERMAID_TRACE_QUEUE_SIZE(int)
Nested Calls (Context Inference)
You don't need to specify source every time. MermaidTrace infers it from the current context.
@trace(source="Client", target="API")
def main():
# Inside here, current participant is "API"
service_call()
@trace(target="Service") # source inferred as "API"
def service_call():
pass
FastAPI Integration
from fastapi import FastAPI
from mermaid_trace.integrations.fastapi import MermaidTraceMiddleware
app = FastAPI()
app.add_middleware(MermaidTraceMiddleware, app_name="MyAPI")
@app.get("/")
async def root():
return {"message": "Hello World"}
CLI Viewer
Visualize your generated .mmd files instantly:
mermaid-trace serve my_flow.mmd
Examples
Check out the examples/ directory for a complete set of demos covering all features:
- Basic Usage: Decorators and class methods.
- Advanced Instrumentation:
@trace_classandpatch_objectfor third-party libraries. - Async & Concurrency: Tracing
asyncioand concurrent tasks. - Error Handling: Stack trace capture and error rendering.
- Intelligent Collapsing: Keeping diagrams clean in loops.
- FastAPI Integration: Middleware for web apps.
- Full Stack App: Comprehensive example with FastAPI, SQLAlchemy, and Pydantic.
- Log Rotation: Handling long-running processes with file rotation.
🤝 Contributing
We welcome contributions! Please see CONTRIBUTING.md for details.
📄 License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mermaid_trace-0.5.3.post0.tar.gz.
File metadata
- Download URL: mermaid_trace-0.5.3.post0.tar.gz
- Upload date:
- Size: 374.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
52213013211d45dbd1c7c1b8c7763101a75aa91fc4e9a577db0ea809a365d0ee
|
|
| MD5 |
388bff39aff94c3ee9cfd6c45ebaff38
|
|
| BLAKE2b-256 |
1609bf91297f80164b824e0104760f186e76d7a2576f3f2dbf77b128077650c5
|
Provenance
The following attestation bundles were made for mermaid_trace-0.5.3.post0.tar.gz:
Publisher:
release.yml on xt765/mermaid-trace
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mermaid_trace-0.5.3.post0.tar.gz -
Subject digest:
52213013211d45dbd1c7c1b8c7763101a75aa91fc4e9a577db0ea809a365d0ee - Sigstore transparency entry: 863175795
- Sigstore integration time:
-
Permalink:
xt765/mermaid-trace@c41cead7761c3f7faba4f23b1ef9d4f2ccb83d12 -
Branch / Tag:
refs/tags/v0.5.3 - Owner: https://github.com/xt765
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@c41cead7761c3f7faba4f23b1ef9d4f2ccb83d12 -
Trigger Event:
release
-
Statement type:
File details
Details for the file mermaid_trace-0.5.3.post0-py3-none-any.whl.
File metadata
- Download URL: mermaid_trace-0.5.3.post0-py3-none-any.whl
- Upload date:
- Size: 40.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
15775d423c3a11c6a488dce6495d9e2c0d97d4c98ce1fdc5a3e2fc0ae7f94e16
|
|
| MD5 |
6a716627f27690317b345f003bb06880
|
|
| BLAKE2b-256 |
9d8b482c94e687c3378621926b0c4634a8f28997ece67e431773b4a33d54f6a0
|
Provenance
The following attestation bundles were made for mermaid_trace-0.5.3.post0-py3-none-any.whl:
Publisher:
release.yml on xt765/mermaid-trace
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mermaid_trace-0.5.3.post0-py3-none-any.whl -
Subject digest:
15775d423c3a11c6a488dce6495d9e2c0d97d4c98ce1fdc5a3e2fc0ae7f94e16 - Sigstore transparency entry: 863175820
- Sigstore integration time:
-
Permalink:
xt765/mermaid-trace@c41cead7761c3f7faba4f23b1ef9d4f2ccb83d12 -
Branch / Tag:
refs/tags/v0.5.3 - Owner: https://github.com/xt765
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@c41cead7761c3f7faba4f23b1ef9d4f2ccb83d12 -
Trigger Event:
release
-
Statement type: