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 โ†’ debug
  • fatal โ†’ 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:

  1. Ring buffer (in-memory): Fast access to current session logs
  2. 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 .jsonl file
  • Clear Buffer: Wipe in-memory buffer (file remains intact)

๐Ÿ“Š Live Streaming

  • New logs auto-append via onLogRecord event 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:

  1. Intelligent Hashing: Normalizes messages to detect duplicates (URLs, timestamps, attempt numbers)
  2. Rate Limiting: Shows first 3 occurrences, then stays silent and counts internally
  3. Periodic Aggregation: Every 5 seconds, emits concise summary with occurrence counts
  4. 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


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:

  1. Check Configuration Guide for setup details
  2. Review Backend Observability for monitoring
  3. See Troubleshooting section below
  4. Consult source code documentation

Troubleshooting

Logs Not Appearing in Control Center

Symptoms: Dashboard actions donโ€™t show logs in Control Center

Checks:

  1. Verify server is running: http://localhost:8765/health
  2. Check browser console for fetch errors
  3. Verify extension polling is active
  4. 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