Skip to main content

Visualize your Python code execution flow as Mermaid Sequence Diagrams.

Project description

MermaidTrace: The Python Logger That Draws Diagrams

🌐 Language: English | 中文

PyPI version Python Versions License CI Status Codecov


📋 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 @trace or @trace_interaction to your functions.
  • Auto-Instrumentation: Use @trace_class to trace a whole class at once.
  • Third-Party Patching: Use patch_object to trace calls inside external libraries.
  • Auto-Diagramming: Generates .mmd files that can be viewed in VS Code, GitHub, or Mermaid Live Editor.
  • Async Support: Works seamlessly with asyncio coroutines.
  • Context Inference: Automatically tracks nested calls and infers source participants using contextvars.
  • 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 RotatingMermaidFileHandler for 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-ID and X-Source headers.
  • 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:


🤝 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.5.3.post0.tar.gz (374.7 kB 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.5.3.post0-py3-none-any.whl (40.1 kB view details)

Uploaded Python 3

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

Hashes for mermaid_trace-0.5.3.post0.tar.gz
Algorithm Hash digest
SHA256 52213013211d45dbd1c7c1b8c7763101a75aa91fc4e9a577db0ea809a365d0ee
MD5 388bff39aff94c3ee9cfd6c45ebaff38
BLAKE2b-256 1609bf91297f80164b824e0104760f186e76d7a2576f3f2dbf77b128077650c5

See more details on using hashes here.

Provenance

The following attestation bundles were made for mermaid_trace-0.5.3.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.5.3.post0-py3-none-any.whl.

File metadata

File hashes

Hashes for mermaid_trace-0.5.3.post0-py3-none-any.whl
Algorithm Hash digest
SHA256 15775d423c3a11c6a488dce6495d9e2c0d97d4c98ce1fdc5a3e2fc0ae7f94e16
MD5 6a716627f27690317b345f003bb06880
BLAKE2b-256 9d8b482c94e687c3378621926b0c4634a8f28997ece67e431773b4a33d54f6a0

See more details on using hashes here.

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

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