Skip to content

Commit 569de1c

Browse files
committed
docs: update docs, comments and blog for v0.6.2
1 parent 302fe0a commit 569de1c

28 files changed

Lines changed: 860 additions & 633 deletions

README.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -211,13 +211,11 @@ login("admin")
211211
Run the built-in CLI tool to preview in real-time (with hot-reload):
212212

213213
```bash
214-
# Basic preview
214+
# Preview a single file (Auto-reload, Pan/Zoom supported)
215215
mermaid-trace serve my_flow.mmd
216216

217-
# Master mode (Directory browsing, zoom, multi-file switching)
218-
mermaid-trace serve . --master
219-
# Or preview a specific file in Master mode
220-
mermaid-trace serve .\mermaid_diagrams\examples\08-log-rotation.mmd --master
217+
# Preview a directory (File browser, Multi-file switching)
218+
mermaid-trace serve .
221219
```
222220

223221
### 🔗 LangChain Integration

README_CN.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -235,13 +235,11 @@ login("admin")
235235
运行代码后,使用内置 CLI 工具实时预览(支持热重载):
236236

237237
```bash
238-
# 基础预览
238+
# 预览单个文件(支持热重载、缩放平移)
239239
mermaid-trace serve my_flow.mmd
240240

241-
# Master 模式 (支持目录浏览、缩放、多文件切换)
242-
mermaid-trace serve . --master
243-
# 或者在 Master 模式下预览特定文件
244-
mermaid-trace serve .\mermaid_diagrams\examples\08-log-rotation.mmd --master
241+
# 预览目录(支持文件浏览、多文件切换)
242+
mermaid-trace serve .
245243
```
246244

247245
### 🔗 LangChain 集成

docs/zh/BLOG.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# MermaidTrace v0.6.2 发布:统一预览体验与分布式追踪支持
2+
3+
**日期**: 2026-02-24
4+
**作者**: 玄同765
5+
6+
我们很高兴地宣布 MermaidTrace v0.6.2 正式发布!本次更新主要集中在统一命令行工具体验、增强 Web 预览功能以及扩展高级应用场景。
7+
8+
## 🚀 核心亮点
9+
10+
### 1. 统一的 CLI 预览体验
11+
12+
在之前的版本中,我们提供了基础的 `http.server` 预览和基于 FastAPI 的 `--master` 模式预览。这种区分不仅增加了用户的学习成本,也导致了功能体验的不一致。
13+
14+
在 v0.6.2 中,我们彻底重构了 CLI:
15+
16+
- **单一入口**:现在只需运行 `mermaid-trace serve`,无论目标是单个文件还是目录,都会默认启动增强型 Web 服务器。
17+
- **全功能体验**:即使只预览一个简单的脚本输出,也能享受到**实时热重载****交互式缩放/平移**以及**美观的 UI**
18+
- **智能降级**:如果未安装 `fastapi``uvicorn`,CLI 会给出清晰的安装提示(`pip install mermaid-trace[server]`)。
19+
20+
```bash
21+
# 预览单个文件(实时刷新)
22+
mermaid-trace serve my_trace.mmd
23+
24+
# 预览项目目录(文件浏览器)
25+
mermaid-trace serve .
26+
```
27+
28+
### 2. 分布式追踪模拟
29+
30+
随着微服务架构的普及,跨服务的调用追踪变得至关重要。我们在 `examples/10_distributed_trace_simulation.py` 中新增了一个完整的分布式追踪示例,演示了如何:
31+
32+
- 在服务间传递 Trace ID。
33+
- 使用 `MermaidTrace` 记录跨服务的调用链路。
34+
- 生成包含多个服务的统一时序图。
35+
36+
### 3. LangChain 集成增强
37+
38+
我们优化了 `LangChain` 集成模块,使其更加健壮和易用:
39+
40+
- **Mock 模式**:即使没有安装 `langchain` 库,用户也可以运行示例代码体验集成效果。
41+
- **类型安全**:修复了与 `langchain-core` 的类型兼容性问题,通过了严格的 Mypy 检查。
42+
43+
### 4. 渲染引擎修复
44+
45+
针对 Python 对象表示中可能包含特殊字符(如 `<User object at 0x...>` 中的 `<``>`)导致 Mermaid 语法解析错误的问题,我们引入了自动 HTML 实体转义机制。现在的图表渲染更加稳定,不再受特殊字符干扰。
46+
47+
## 📚 下一步计划
48+
49+
我们将继续探索更多高级场景,包括:
50+
51+
- **性能分析视图**:在时序图中集成函数执行耗时热力图。
52+
- **更丰富的框架支持**:计划增加对 Django 和 Flask 的原生支持。
53+
54+
感谢所有社区贡献者的支持!欢迎在 GitHub 上提交 Issue 或 PR。
55+
56+
---
57+
58+
*立即升级体验:*
59+
```bash
60+
pip install -U mermaid-trace[server]
61+
```

docs/zh/UPDATE_LOG.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,30 @@
11
# 更新日志 (UPDATE_LOG)
22

3+
## [2026-02-24] - CLI 重构、Web 预览增强与生态扩展
4+
5+
### 核心架构升级
6+
- **CLI 统一重构**:
7+
- 彻底重写了命令行接口,废弃了基于 `http.server` 的简易实现,统一使用基于 FastAPI 的增强型服务器。
8+
- 移除了 `--master` 参数,现在 `mermaid-trace serve` 默认开启全功能 Web 预览(支持热重载、缩放、平移)。
9+
- 支持单文件模式:`mermaid-trace serve file.mmd` 也能享受完整的 Web UI 体验。
10+
- **Mermaid 渲染修复**:
11+
- 修复了 Python 对象表示(如 `<User>`)包含特殊字符导致 Mermaid 语法解析错误的问题。
12+
- 实现了 HTML 实体转义机制,确保 `<``>` 等字符在图表中正确显示。
13+
14+
### 生态集成与示例
15+
- **LangChain 集成增强**:
16+
- 优化了 `examples/09_langchain_integration.py`,支持在未安装 LangChain 环境下的 Mock 运行模式,方便用户体验。
17+
- 修复了类型检查问题,确保集成代码的健壮性。
18+
- **新增高级示例**:
19+
- `10_distributed_trace_simulation.py`: 演示了如何在分布式系统中传递 Trace Context。
20+
- `11_custom_masking.py`: 展示了如何自定义数据脱敏逻辑(如递归脱敏)。
21+
- `12_config_from_file.py`: 演示了从 JSON 文件加载配置。
22+
23+
### 文档与规范
24+
- **中英文文档同步**: 更新了 `README``USER_GUIDE`,反映了 CLI 的最新用法。
25+
- **代码注释**: 全面更新了 `cli.py``server.py` 的中文代码注释,详细解释了服务器实现原理。
26+
- **依赖管理**: 在 `pyproject.toml` 中新增了 `server` extras,方便用户一键安装服务器依赖 (`pip install mermaid-trace[server]`)。
27+
328
## [2026-02-02] - QA 强化与文档精化 (Refinement)
429

530
### 代码质量强化

examples/01_basic_usage.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,5 +53,9 @@ def main() -> None:
5353
if __name__ == "__main__":
5454
print("Running basic example...")
5555
main()
56-
print("Done! Open 'basic_flow.mmd' to see the diagram.")
56+
print("Done! Open 'mermaid_diagrams/examples/basic_flow.mmd' to see the diagram.")
5757
print("Check the file content to verify 'password' and 'secret_key' are masked!")
58+
print(
59+
"\n💡 TIP: Run the live preview server to see the diagram update in real-time:"
60+
)
61+
print(" mermaid-trace serve mermaid_diagrams/examples/basic_flow.mmd")

examples/09_langchain_integration.py

Lines changed: 55 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@
2626

2727
def demo_with_mock_langchain() -> None:
2828
"""
29-
Since we don't want to require langchain-core to run this example,
30-
we mock the behavior of a LangChain chain calling the handler.
29+
Mock behavior of a LangChain chain calling the handler.
30+
Used when langchain is not installed.
3131
"""
32-
print("🚀 Starting LangChain Mock Trace...")
32+
print("🚀 Starting LangChain Mock Trace (No langchain installed)...")
3333

3434
# Initialize the handler
3535
handler = MermaidTraceCallbackHandler(host_name="MyApp")
@@ -67,25 +67,59 @@ def __init__(self) -> None:
6767
print("--- Chain End ---")
6868
handler.on_chain_end(outputs={"answer": "MermaidTrace is a visualization tool."})
6969

70-
print(
71-
"\n✅ Done! Check 'mermaid_diagrams/examples/langchain_trace.mmd' for the result."
72-
)
70+
71+
def demo_with_real_langchain() -> None:
72+
"""
73+
Runs a real LangChain chain if dependencies are present.
74+
"""
75+
try:
76+
from langchain_openai import ChatOpenAI # type: ignore
77+
from langchain_core.prompts import ChatPromptTemplate
78+
from langchain_core.output_parsers import StrOutputParser
79+
except ImportError:
80+
print("❌ LangChain dependencies missing for real demo.")
81+
return
82+
83+
api_key = os.getenv("OPENAI_API_KEY")
84+
if not api_key:
85+
print("⚠️ OPENAI_API_KEY not found. Skipping real API call.")
86+
print(" Run: set OPENAI_API_KEY=sk-... to try the real demo.")
87+
# Fallback to mock if no key
88+
demo_with_mock_langchain()
89+
return
90+
91+
print("🚀 Starting REAL LangChain Trace...")
92+
93+
# 1. Setup Chain
94+
handler = MermaidTraceCallbackHandler(host_name="LangChainApp")
95+
llm = ChatOpenAI(api_key=api_key, model="gpt-3.5-turbo")
96+
prompt = ChatPromptTemplate.from_template("Tell me a short joke about {topic}")
97+
chain = prompt | llm | StrOutputParser()
98+
99+
# 2. Invoke with Handler
100+
print("Invoking chain...")
101+
result = chain.invoke({"topic": "debugging"}, config={"callbacks": [handler]})
102+
print(f"Result: {result}")
73103

74104

75105
if __name__ == "__main__":
76-
demo_with_mock_langchain()
106+
# Check for LangChain availability
107+
try:
108+
import langchain_core # noqa: F401
109+
import langchain_openai # noqa: F401
110+
111+
HAS_LANGCHAIN = True
112+
except ImportError:
113+
HAS_LANGCHAIN = False
114+
115+
if HAS_LANGCHAIN:
116+
demo_with_real_langchain()
117+
else:
118+
demo_with_mock_langchain()
119+
print(
120+
"\n💡 TIP: Install 'langchain-openai' and set OPENAI_API_KEY to run the real demo!"
121+
)
77122

78-
# Instructions for real LangChain usage:
79-
"""
80-
# To use with real LangChain:
81-
from langchain_openai import ChatOpenAI
82-
from langchain_core.prompts import ChatPromptTemplate
83-
84-
handler = MermaidTraceCallbackHandler()
85-
llm = ChatOpenAI()
86-
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
87-
chain = prompt | llm
88-
89-
# Just pass the handler to the invoke method
90-
chain.invoke({"topic": "bears"}, config={"callbacks": [handler]})
91-
"""
123+
print(
124+
"\n✅ Done! Check 'mermaid_diagrams/examples/langchain_trace.mmd' for the result."
125+
)
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
"""
2+
Distributed Tracing Simulation.
3+
Demonstrates:
4+
1. Simulating a microservices architecture (Service A calling Service B).
5+
2. Propagating the Trace ID across service boundaries (e.g., via HTTP headers).
6+
3. Linking distributed logs into a single coherent Mermaid diagram.
7+
"""
8+
9+
import time
10+
import uuid
11+
from typing import Dict, Any
12+
from mermaid_trace import trace, configure_flow
13+
from mermaid_trace.core.context import LogContext
14+
15+
# Setup tracing to a single file to see the full picture
16+
configure_flow("mermaid_diagrams/examples/distributed_trace.mmd")
17+
18+
19+
# --- Simulated Network Layer ---
20+
21+
22+
class NetworkClient:
23+
"""
24+
Simulates an HTTP client that automatically injects the current Trace ID header.
25+
"""
26+
27+
@trace(source="ServiceA", target="Network", action="HTTP POST")
28+
def post(self, url: str, data: Dict[str, Any]) -> Dict[str, Any]:
29+
# 1. Get current trace ID
30+
current_trace_id = LogContext.current_trace_id()
31+
32+
# 2. Inject into headers (simulation)
33+
headers = {"X-Trace-ID": current_trace_id}
34+
print(f"[Network] Sending request to {url} with Trace ID: {current_trace_id}")
35+
36+
# 3. Simulate network call to Service B
37+
if url == "http://service-b/api/process":
38+
return service_b_entrypoint(headers, data)
39+
return {"error": "404 Not Found"}
40+
41+
42+
# --- Service B (The Called Service) ---
43+
44+
45+
@trace(source="Network", target="ServiceB", action="Handle Request")
46+
def service_b_entrypoint(
47+
headers: Dict[str, str], payload: Dict[str, Any]
48+
) -> Dict[str, Any]:
49+
"""
50+
Simulates the entry point (e.g., FastAPI middleware) of Service B.
51+
It extracts the Trace ID and restores the context.
52+
"""
53+
# 1. Extract Trace ID from headers
54+
incoming_trace_id = headers.get("X-Trace-ID")
55+
56+
if incoming_trace_id:
57+
# 2. RESTORE CONTEXT: Important!
58+
# This links Service B's actions to the original trace started in Service A.
59+
LogContext.set_trace_id(incoming_trace_id)
60+
print(f"[ServiceB] Resumed context with Trace ID: {incoming_trace_id}")
61+
else:
62+
# Fallback: Start a new trace if no ID provided
63+
new_id = str(uuid.uuid4())
64+
LogContext.set_trace_id(new_id)
65+
print(f"[ServiceB] No Trace ID found, started new: {new_id}")
66+
67+
# 3. Call internal business logic
68+
return process_data(payload)
69+
70+
71+
@trace(target="ServiceB.Logic")
72+
def process_data(data: Dict[str, Any]) -> Dict[str, Any]:
73+
time.sleep(0.1)
74+
return {"status": "processed", "result": f"Processed {data['item']}"}
75+
76+
77+
# --- Service A (The Caller Service) ---
78+
79+
80+
@trace(source="Client", target="ServiceA", action="Start Job")
81+
def run_job() -> None:
82+
client = NetworkClient()
83+
84+
print("[ServiceA] Starting job...")
85+
item = {"item": "Order-123", "amount": 99.9}
86+
87+
# This call will propagate the trace ID internally via our simulated client
88+
response = client.post("http://service-b/api/process", item)
89+
90+
print(f"[ServiceA] Got response: {response}")
91+
92+
93+
if __name__ == "__main__":
94+
print("Simulating distributed tracing between Service A and Service B...")
95+
run_job()
96+
print("\nCheck 'mermaid_diagrams/examples/distributed_trace.mmd'.")
97+
print("You should see a continuous flow from Client -> ServiceA -> ServiceB.")

0 commit comments

Comments
 (0)