← Back to PRs

#12966: feat(logging): Add session context and breadcrumbs to error logs

by trevorgordon981 open 2026-02-10 00:16 View on GitHub →
stale
# PR: feat(logging): Add session context and breadcrumbs to error logs ## Summary Adds enhanced error context tracking for better debugging in multi-session and multi-agent setups. This module provides structured error context with session correlation, operation tracing, and automatic sanitization. ## Motivation In multi-agent or multi-session deployments, errors can be difficult to trace back to their source. This feature adds: - **Session keys** to correlate errors to specific sessions - **Breadcrumbs** to trace the path leading to an error - **Automatic sanitization** to safely transmit errors without leaking secrets ## Features ### Operation Context Stack ```typescript import { pushOperation, popOperation, addBreadcrumb } from './error-context.js'; // Track operation context pushOperation({ sessionKey: 'sess-abc123', operation: 'tool-exec', tool: 'exec' }); addBreadcrumb('Starting command execution'); addBreadcrumb('Command completed, parsing output'); // ... error occurs ... popOperation(); ``` ### Contextual Errors ```typescript import { createContextualError, formatContextualError } from './error-context.js'; const err = createContextualError('Tool execution failed', { code: 'TOOL_EXEC_FAIL', context: { sessionKey: 'sess-abc123', operation: 'exec' } }); console.log(formatContextualError(err)); // Output: [sess-abc] {exec} ERR_TOOL_EXEC_FAIL Tool execution failed // Breadcrumbs: // [2026-02-09T00:00:00.000Z] Starting command execution // [2026-02-09T00:00:01.000Z] Command completed, parsing output ``` ### Automatic Sanitization ```typescript import { sanitizeError, sanitizeContextualErrorForSlack } from './error-context.js'; // Redacts tokens, secret URLs, and sensitive file paths const result = sanitizeError(new Error('Failed with token abc123...def456')); // result.message: "Failed with token [REDACTED_TOKEN]" // Safe for external delivery (Slack, webhooks, etc.) const safeErr = sanitizeContextualErrorForSlack(contextualError); ``` ## API | Function | Description | |----------|-------------| | `pushOperation(ctx)` | Push operation context onto stack | | `popOperation()` | Pop current operation context | | `getCurrentOperation()` | Get current operation context | | `clearOperationStack()` | Clear all operation contexts | | `addBreadcrumb(message)` | Add breadcrumb to current operation | | `sanitizeError(err)` | Sanitize error for safe transmission | | `createContextualError(msg, opts)` | Create error with context | | `formatContextualError(err)` | Format error for human-readable logs | | `sanitizeContextualErrorForSlack(err)` | Sanitize contextual error for external delivery | ## Types ```typescript type OperationContext = { sessionKey?: string; operation?: string; tool?: string; timestamp?: number; breadcrumbs?: string[]; }; type ContextualError = { message: string; code?: string; context: OperationContext; originalError?: Error; sanitized?: boolean; }; ``` ## Benefits 1. **Debugging**: Easily correlate errors to specific sessions in multi-agent deployments 2. **Tracing**: Follow operation chains with breadcrumb trails 3. **Security**: Automatic redaction prevents secret leakage in error reports 4. **Flexibility**: Works standalone or integrates with existing logging ## Performance - **Negligible overhead**: Simple array operations for context stack - **No async operations**: Purely synchronous, no event loop impact - **Memory efficient**: Breadcrumbs are timestamp-prefixed strings ## Test Coverage 16 test cases covering: - Operation stack management (push/pop/clear) - Breadcrumb tracking - Token/URL/path sanitization - Context inheritance from stack - Formatted output generation - Slack-safe sanitization ## Backward Compatibility - **No breaking changes**: New standalone module - **No dependencies**: Zero imports, self-contained - **Optional adoption**: Consumers can gradually integrate ## Files Changed - `src/logging/error-context.ts` - Main module (156 lines) - `src/logging/error-context.test.ts` - Tests (189 lines) ## Branch `feature/enhanced-error-context` based on `upstream/main` ## PR Metadata - **Title**: feat(logging): Add session context and breadcrumbs to error logs - **Labels**: enhancement, logging, debugging - **Reviewers**: (maintainers) <!-- greptile_comment --> <h2>Greptile Overview</h2> <h3>Greptile Summary</h3> This PR introduces a new `src/logging/error-context.ts` module plus unit tests to support attaching session/operation context and breadcrumb trails to errors, formatting those contextual errors for logs, and sanitizing error messages/breadcrumbs for external delivery (e.g., Slack). The module is currently standalone and not wired into any existing logging pipeline in `src/`, so its impact depends on follow-up integration. The core API (push/pop stack, breadcrumb capture, contextual error creation/formatting, and sanitization) is straightforward, but there are a couple of correctness issues around concurrency/isolation and sanitization behavior that should be addressed before merging. <h3>Confidence Score: 2/5</h3> - Not safe to merge as-is due to incorrect context isolation across concurrent operations. - The module uses a process-global mutable stack for operation context, which will produce wrong/merged context in real multi-session or overlapping async usage. Additionally, sanitization behavior is currently overly broad (redacting many non-secret identifiers) and reports inconsistent sanitized status for non-Error inputs, making downstream behavior hard to trust. - src/logging/error-context.ts <!-- greptile_other_comments_section --> <sub>(5/5) You can turn off certain types of comments like style [here](https://app.greptile.com/review/github)!</sub> **Context used:** - Context from `dashboard` - CLAUDE.md ([source](https://app.greptile.com/review/custom-context?memory=fd949e91-5c3a-4ab5-90a1-cbe184fd6ce8)) - Context from `dashboard` - AGENTS.md ([source](https://app.greptile.com/review/custom-context?memory=0d0c8278-ef8e-4d6c-ab21-f5527e322f13)) <!-- /greptile_comment -->

Most Similar PRs