# MCP Server Logging Examples
This directory contains practical examples demonstrating how to integrate correlation logging into the ComfyUI MCP Server architecture.
## Examples Overview
### [01_simple_tool_logging.py](01_simple_tool_logging.py)
**Correlation tracking for MCP tools (Interface Layer)**
Demonstrates:
- Setting correlation IDs at tool entry
- Using `get_global_logger()` for correlation-aware logging
- Automatic correlation ID injection in all log messages
- Async context isolation
- Error logging with correlation tracking
**When to use:** For all MCP tool functions (`@mcp.tool()` decorated functions)
### [02_manager_logging.py](02_manager_logging.py)
**Manual logging for business logic (Logic Layer)**
Demonstrates:
- Manager class initialization with logger
- Cache hit/miss logging with correlation IDs
- Parameter validation logging
- Resource cleanup logging
- Structured messages with contextual information
**When to use:** For managers, orchestrators, and business logic classes
### [03_http_logging.py](03_http_logging.py)
**External API call logging**
Demonstrates:
- HTTP request/response logging with correlation tracking
- Timing and duration tracking
- Status code and response size logging
- Error handling with HTTP context
- Progress logging for long-running operations
**When to use:** For ComfyUI client or any external API interactions
### [04_parameter_sanitization.py](04_parameter_sanitization.py)
**Parameter logging with sensitive data redaction**
Demonstrates:
- Using `@log_call` decorator for parameter logging
- Automatic sanitization of sensitive parameters (passwords, tokens, API keys)
- Manual redaction patterns when needed
- Environment-based parameter logging control
**When to use:**
- When debugging tools that accept sensitive data
- For audit trails that need parameter tracking
- During development (disable in production)
**Run**:
```bash
# Standard run
python 04_parameter_sanitization.py
# With debug logging enabled
DEBUG_LOGGING=true python 04_parameter_sanitization.py
```
**Example output**:
```
[abc-123-def-456] [tool] configure_webhook - ENTER params={'url': 'https://example.com/webhook', 'webhook_secret': '[REDACTED]', 'timeout': 60}
[abc-123-def-456] [tool] configure_webhook - SUCCESS (0.100s)
```
## Running the Examples
Each example is self-contained and can be run independently:
```bash
# Install dependencies first (if running standalone)
uv sync
# Run individual examples
python 01_simple_tool_logging.py
python 02_manager_logging.py
python 03_http_logging.py
python 04_parameter_sanitization.py
```
## Integration Pattern
```
┌─────────────────────────────────────────────────┐
│ MCP Server Layers │
├─────────────────────────────────────────────────┤
│ │
│ Protocol Layer (server.py) │
│ └─ setup_correlation_logging() at startup │
│ Manual logging with correlation support │
│ │
├─────────────────────────────────────────────────┤
│ │
│ Interface Layer (tools/*.py) │
│ └─ Set correlation ID at entry │
│ Use get_global_logger(__name__) │
│ Example: 01_simple_tool_logging.py │
│ │
├─────────────────────────────────────────────────┤
│ │
│ Logic Layer (orchestrators/) │
│ └─ Use get_global_logger(__name__) │
│ Correlation IDs propagate automatically │
│ Example: 02_manager_logging.py │
│ │
├─────────────────────────────────────────────────┤
│ │
│ Routes Layer (routes/) │
│ └─ Use @log_call decorator │
│ Correlation IDs automatically included │
│ Example: 03_http_logging.py │
│ │
└─────────────────────────────────────────────────┘
```
## Key Patterns Demonstrated
### 1. Correlation ID Flow
```python
# Tools: Set correlation ID at entry
correlation_id = generate_correlation_id()
set_correlation_id(correlation_id)
# All layers: Use global logger
logger = get_global_logger(__name__)
logger.info("Message") # Automatic [correlation-id] prefix
```
### 2. Async Context Isolation
- Each async execution path maintains isolated correlation context
- Concurrent workflows tracked independently
- No race conditions or ID mixing
### 3. Zero Boilerplate
- No manual correlation ID handling in logging calls
- Context variables propagate automatically
- Works seamlessly with existing logging code
### 4. Error Handling
- Stack traces automatically include correlation IDs
- Contextual error metadata
- Duration tracking even on failure
## Correlation Logging Architecture
### How It Works
1. **Global Setup** (server.py):
```python
setup_correlation_logging() # Call once at startup
```
2. **Custom Logger Class**:
- `CorrelationLogger` extends `logging.Logger`
- Overrides `_log()` to inject correlation ID prefix
- Automatically applied to all future loggers
3. **Context Management**:
- Uses `contextvars.ContextVar` for async-safe storage
- Isolated contexts per async execution path
- No thread-safety issues
### Benefits
- ✅ **Zero boilerplate** - No manual correlation handling
- ✅ **Async-safe** - Works with FastMCP's async execution
- ✅ **Automatic** - All loggers include correlation IDs
- ✅ **Standard** - Uses Python stdlib only (no external deps)
## Next Steps
After reviewing these examples:
1. **Read the main skill**: [../SKILL.md](../SKILL.md)
2. **Review architecture**: [../../../AGENTS.md](../../../AGENTS.md)
3. **Start integration**: Add logging to your MCP tools and orchestrators
4. **Configure for production**: Set up log rotation and levels
## Questions or Issues?
See the [main skill documentation](../SKILL.md) for:
- Configuration options
- Migration strategy
- Best practices
- Troubleshooting