# BranchPy Logging System
Version: 1.1.1
Last Updated: January 23, 2026
Status: Production
Overview
BranchPy provides a comprehensive structured logging infrastructure that serves three distinct purposes across the entire platform ecosystem:
1. Control Center Logging (v0.8.5.5+)
Centralized log viewer in VS Code Control Center that collects logs from all components:
- VS Code Extension (📦) - Extension operations, commands, notifications
- Dashboard/Web UI (ðŸŒ) - React app events, server connections, user actions
- CLI (💻) - Command-line operations and analysis results
- Daemon (🔄) - Background service events and file watching
- Server (🖥ï¸) - FastAPI server operations and API requests
Features:
- Real-time log streaming with 5-second polling
- Source badges for visual identification
- Expandable JSON details
- LogsPanel v3 with advanced filtering and export capabilities
2. Structured Development Logging
Application logs for debugging, telemetry, and performance monitoring:
- JSONL format for machine-readability
- Ring buffer architecture with file rotation
- Configurable verbosity levels (TRACE through FATAL)
- Redaction of sensitive data (emails, tokens, paths)
- Support bundle generation for diagnostics
3. Team Audit Log (v0.8.1+)
Tamper-evident, hash-chained audit trail for compliance and collaboration:
- Captures who/what/when/where/why
- Multi-user identity and RBAC
- Pluggable sinks: local file, HTTPS, Git repository
- Session replay and verification capabilities
Quick Start
Python Logging
import branchpy.logs as logs
# Basic logging
logs.info("analysis.started", "Starting deep analysis",
project_path="/path/to/game")
logs.warn("config.deprecated", "Deprecated field detected",
field="legacy_mode")
logs.error("validation.failed", "Invalid configuration",
reason="missing required field")
# Context management
logs.set_context(component="cli", session="abc123")
# Temporary TRACE elevation (for debugging)
logs.enable_trace(duration_minutes=5)
# Control Center integration (automatic when dashboard running)
logs.enable_controlcenter(url="http://localhost:8765")
# Query log buffer
events = logs.find_events_range("DEBUG", "ERROR",
component="cli", limit=50)
TypeScript Logging (VS Code Extension)
import * as log from './log';
// Initialize logging
log.initLogging(outputChannel);
// Log events
log.info('analysis.complete', 'Deep analysis finished', {
findings: 42,
duration_ms: 1523
});
log.error('config.invalid', 'Configuration file not found', {
file: 'branchpy.toml',
expected: expectedPath
});
// Get recent logs from ring buffer
const recent = log.getRecentLogs();
// Tail log file
const persisted = log.tailFile('vscode', 100);
Dashboard Logging (React)
import { logger } from '../utils/logger';
logger.info('Connected to server', {
url: serverUrl,
attempts: reconnectCount
});
logger.error('Server connection failed', {
error: error.message,
retryDelay: delay
});
Log Levels
| Level | Value | Icon | Usage | Fallback |
|---|---|---|---|---|
| TRACE | 5 | 🔎 | High-volume diagnostic start/stop events | → debug if backend rejects |
| DEBUG | 10 | 🔠| Developer diagnostics and troubleshooting | — |
| INFO | 20 | ✅ | Normal operations, progress indicators | — |
| WARN | 30 | âš ï¸ | Non-critical anomalies, deprecations | — |
| ERROR | 40 | ⌠| Operation failures, exceptions | — |
| FATAL | 50 | 💀 | Unrecoverable states requiring operator attention | → error if backend rejects |
FATAL Policy
Reserved for unrecoverable states that require immediate operator attention:
- Daemon binary missing or corrupted
- Configuration file corruption
- Delta chain integrity failure
- Critical resource exhaustion
JSONL Format
All logs are stored in JSON Lines format (one JSON object per line):
{"ts":"2026-01-23T14:32:11.382Z","level":"INFO","component":"cli","event":"analysis.started","msg":"Starting deep analysis","attrs":{"project_path":"/path/to/game"},"ids":{"session":"abc123","run":"xyz789"},"host":{"os":"Windows","node":"DESKTOP-123","bpy":"1.1.1"}}
{"ts":"2026-01-23T14:32:15.629Z","level":"WARN","component":"cli","event":"config.deprecated","msg":"Deprecated field detected","attrs":{"field":"legacy_mode"},"ids":{"session":"abc123","run":"xyz789"},"host":{"os":"Windows","node":"DESKTOP-123","bpy":"1.1.1"}}
LogRecord Structure
interface LogRecord {
ts: string; // ISO 8601 timestamp (UTC)
level: Level; // TRACE | DEBUG | INFO | WARN | ERROR | FATAL
component: string; // vscode, cli, daemon, etc.
sub?: string; // Optional subcomponent
event: string; // Dot-notation event name
msg?: string; // Human-readable message
attrs?: Record<string, any>; // Custom attributes
source: { // Caller information
file: string;
line: number;
func: string;
};
ids: { // Correlation IDs
install?: string;
session?: string;
run?: string;
project?: string;
};
host: { // Environment metadata
os: string;
node: string;
vscode?: string; // VS Code version (if applicable)
bpy: string; // BranchPy version
};
}
Control Center Integration
Architecture
All Python logs automatically appear in the VS Code Control Center when the dashboard is running:
Python/CLI/Daemon → logs.info/error/etc
↓
_write_event() → _write_to_controlcenter()
↓ POST /api/v1/logs/dashboard
Server API (in-memory buffer, max 100 entries)
↓ GET polling every 5s
VS Code Extension (fetchDashboardLogs)
↓ postLog(msg, source, details)
Control Center Panel
└─ [14:32:11] ✅ 💻 analysis.started: Starting deep analysis
└─ { project_path: "/path/to/game", ... }
Source Badges
| Source | Badge | Description |
|---|---|---|
vscode |
📦 | VS Code extension operations |
web |
🌠| Dashboard/Web UI events |
cli |
💻 | Command-line operations |
daemon |
🔄 | Background daemon service |
server |
ðŸ–¥ï¸ | FastAPI server operations |
Automatic Fallback
If the backend server rejects custom log levels, BranchPy automatically retries once with standard levels:
trace→debugfatal→error
LogsPanel v3 — Advanced Log Viewer
Access: Control Center → “Show Logs” button OR Command Palette → “BranchPy: Show Logs”
Key Features
🔄 Refresh Button
Manually reload last 100 log entries from persistent JSONL file. Useful after extension reload or when ring buffer is empty.
📠Persistent Log Loading
Dual-source architecture:
- Ring buffer (in-memory): Fast access to current session logs
- File tail (disk): Fallback when ring buffer is empty
Automatically loads last 100 entries on panel open and survives extension reloads.
🕠Local Timestamp Display
Converts UTC timestamps to user’s local timezone:
- Format:
MM/DD/YYYY HH:MM:SS Timezone - Example:
01/23/2026 14:32:11 America/New_York
ðŸŽ›ï¸ Advanced Filtering
- Log Level: Filter by TRACE, DEBUG, INFO, WARN, ERROR, or FATAL
- Component: Filter by vscode, cli, daemon, dashboard, etc.
- Search: Text search across events, messages, and attributes
- Errors Only: Toggle to show only WARN/ERROR/FATAL
💾 Export Capabilities
- Copy to Clipboard: Copy all filtered logs
- Export JSONL: Download filtered logs as
.jsonlfile - Clear Buffer: Wipe in-memory buffer (file remains intact)
📊 Live Streaming
- New logs auto-append via
onLogRecordevent emitter - No manual refresh needed for current session logs
- Real-time updates as events occur
🧮 Buffer Management
- 10,000 entry max buffer: Auto-prunes oldest entries when limit reached
- Tail 500 display: Shows last 500 filtered entries for UI performance
- Stats display: “Showing X of Y events” counter
- Auto-scroll: Scrolls to bottom on new log arrival
Log File Locations
- Windows:
%LOCALAPPDATA%\BranchPy\logs\vscode.jsonl - Unix/macOS:
~/.branchpy/logs/vscode.jsonl
Smart Logging & Rate Management
SmartLogger (VS Code Extension)
Prevents console flooding from repetitive messages using intelligent deduplication:
Features:
- Intelligent Hashing: Normalizes messages to detect duplicates (URLs, timestamps, attempt numbers)
- Rate Limiting: Shows first 3 occurrences, then stays silent and counts internally
- Periodic Aggregation: Every 5 seconds, emits concise summary with occurrence counts
- Auto-Cleanup: Removes entries older than 1 minute to prevent memory leaks
Before (Flooding):
[Extension] WebSocket connected: ws://...
[Extension] WebSocket connected: ws://...
[Extension] WebSocket connected: ws://...
... (100+ identical lines)
After (Clean):
[Extension] [14:32:11] INFO: WebSocket connected: ws://...
[Extension] [14:32:11] INFO: Preflight FRESH ✓ READY
... (5 seconds of silence) ...
[Extension] [14:32:16] INFO: 📊 Aggregated Logs (last 5s):
• Connected: ws://X (×15 over 4.8s)
• FRESH ✓ READY (×3 over 5.1s)
TRACE Rate Limiting (Python)
Core Python logger enforces per-second cap on TRACE events (default 500/sec):
from branchpy import logs
# Adjust rate limit
logs.set_trace_rate_limit(200) # Tighten to 200/sec
# Excess events dropped silently
# Single WARN summary emitted: logs.trace_rate_limited
Metrics & Telemetry
Per-Level Counters
from branchpy import logs
# Get metrics snapshot
metrics = logs.get_metrics()
# Returns: {'TRACE': 1523, 'DEBUG': 42, 'INFO': 156, ...}
# Reset counters
logs.reset_metrics()
Telemetry Export
When telemetry is enabled, BranchPy exports periodic metrics:
{"event":"logging.metrics","ts":"2026-01-23T14:32:11Z","attrs":{"TRACE":1523,"DEBUG":42,"INFO":156,"WARN":8,"ERROR":2,"FATAL":0}}
High-volume TRACE counters auto-reset after export to bound memory usage.
Configuration
See Configuration Guide for detailed settings:
- Log levels and sinks
- File rotation policies
- Redaction modes
- Ring buffer sizes
- Rate limiting
Performance
| Metric | Target | Status |
|---|---|---|
| Append Latency (P50) | ≤ 1.0ms | ✅ Validated |
| Append Latency (P99) | ≤ 5ms | ✅ Validated |
| Ring Buffer Append | O(1) | ✅ Deque push |
| Metrics Increment | O(1) | ✅ Lock-protected |
| Console Reduction | 80-95% | ✅ SmartLogger |
Related Documentation
- Configuration Guide - Log levels, sinks, rotation
- Backend Observability - Health checks, monitoring
- Audit Logging - Team audit trail (separate system)
- API Reference - Server logging endpoints
Migration Notes
From v1.0.0 to v1.1.1
No breaking changes. New features:
- Enhanced FATAL policy alignment
- Improved Control Center fallback handling
- Performance optimizations in SmartLogger
- Extended metrics export
Upgrading Python Code
# Old (still works)
import logging
logging.info("message")
# New (recommended)
import branchpy.logs as logs
logs.info("event.name", "message", key="value")
Upgrading TypeScript Code
// Old (still works)
console.log("message");
// New (recommended)
import * as log from './log';
log.info('event.name', 'message', { key: 'value' });
Support
For questions or issues:
- Check Configuration Guide for setup details
- Review Backend Observability for monitoring
- See Troubleshooting section below
- Consult source code documentation
Troubleshooting
Logs Not Appearing in Control Center
Symptoms: Dashboard actions don’t show logs in Control Center
Checks:
- Verify server is running:
http://localhost:8765/health - Check browser console for fetch errors
- Verify extension polling is active
- Check server logs for POST requests to
/api/v1/logs/dashboard
Solution:
# Restart dashboard
branchpy dashboard stop
branchpy dashboard start
High Memory Usage
Symptoms: Extension or server consuming excessive memory
Checks:
- Extension log buffer: max 10,000 entries
- Server log buffer: max 100 entries
- Polling interval: 5 seconds
Solution: Logs auto-prune when limits reached (FIFO). If issue persists, reduce ring_buffer_size in configuration.
Missing Log Details
Symptoms: Logs show but details object is empty
Check: Verify details object is JSON-serializable (no circular references, DOM elements, etc.)
Changelog
v1.1.1 (January 23, 2026)
- Enhanced FATAL policy alignment across components
- Improved Control Center automatic fallback handling
- Performance optimizations in SmartLogger
- Extended metrics export with high-volume auto-reset
- Documentation consolidation and cross-referencing
v1.0.0 (November 8, 2025)
- Full level fidelity (TRACE, FATAL) with graceful downgrade
- TRACE rate limiting with summary WARN event
- Telemetry metrics export integration
- Range query API support
- Documentation for activation helpers
v0.8.5.5 (November 4, 2025)
- Initial Control Center centralized logging
- LogsPanel v3 with Refresh button and persistent loading
- Python logging system integration
- Source badges and expandable details
- Dashboard logger service
- Server log collection API
Source: Consolidated from
docs/v1.1.0/Logging/(README.md, BranchPy_Logging_Documentation.md, CONTROL_CENTER_LOGGING.md)
Maintained by: BranchPy Core Team
License: Proprietary