Skip to content

Commit fe09c33

Browse files
malibioclaude
andauthored
Refactor logging/debugging approach across codebase (#733)
* WIP: Refactor logging to use Logger utility - Phase 1 complete ## Completed in This Session - [x] Enhanced Logger utility with environment-aware defaults - Production: warn level (clean console) - Development: debug level (all logs) - Tests: disabled (better performance) - Added group(), groupEnd(), time() methods - [x] Migrated key frontend services to Logger - browser-sync-service.ts (16 statements) - app-initialization.ts (5 statements) - navigation-service.ts (5 statements) - [x] Migrated schema-plugin-loader.ts (6 statements) - [x] Updated test expecting console.error (now uses logger) ## Remaining Work - [ ] Migrate remaining services (shared-node-store, reactive-node-service, etc.) - [ ] Migrate frontend components (~35 statements) - [ ] Migrate node type files (~17 statements) - [ ] Migrate remaining plugins (~3 statements) - [ ] Standardize Rust backend tracing ## Current State - Files modified: 7 (logger.ts, 4 services, 1 plugin, 1 test) - Tests status: All 1569 passing - Quality checks: Passing (eslint, svelte-check, clippy) - Remaining console statements in lib: ~204 (down from 328+) ## Context for Next Session The Logger utility is fully enhanced and working. Key services that were causing production console noise are migrated. The remaining work is methodical migration of: 1. Services with internal log() helpers (layout-persistence, tab-persistence, etc.) 2. Console.error/warn calls (appropriate levels, just need Logger consistency) 3. Components and node type files 4. Rust backend println!/eprintln! → tracing ## Acceptance Criteria Status From issue #363: - [x] Logger utility enhanced with environment-aware defaults - [x] Production console clean for migrated services - [ ] All frontend services use Logger - [ ] All frontend components use Logger - [ ] All frontend plugins use Logger - [ ] Backend library code uses tracing consistently 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * Complete logging refactor: Migrate all console.* to Logger utility ## Changes - Migrate 40+ files from console.* to Logger utility - Remove unused performance-monitor.ts (dead code) - Update tests to verify behavior instead of log output (Logger is intentionally silenced during tests) ## Files Modified ### Services (core migration) - layout-persistence-service.ts - tab-persistence-service.ts - node-expansion-coordinator.ts - optimistic-operation-manager.svelte.ts - backend-adapter.ts - cursor-positioning-service.ts - keyboard-command-registry.ts - tauri-sync-listener.ts - shared-node-store.svelte.ts - reactive-node-service.svelte.ts - content-processor.ts - performance-tracker.ts ### Components - base-node.svelte, base-node-viewer.svelte - app-shell.svelte, tab-system.svelte, pane-content.svelte - backlinks-panel.svelte, custom-entity-node.svelte - schema-property-form.svelte, task-schema-form.svelte - autocomplete-modal.svelte, node-service-context.svelte - cursor-positioning.ts ### Plugins & Utils - plugin-registry.ts, core-plugins.ts - database-write-queue.ts, marked-config.ts - navigation.ts, layout.ts, reactive-structure-tree.svelte.ts ### Tests Updated - core-plugins.test.ts, plugin-registry.test.ts - keyboard-command-registry.test.ts, mcp-integration.test.ts - shared-node-store.test.ts, database-write-queue.test.ts ## Remaining Console Statements (Intentional) - logger.ts: The Logger utility itself - developer-inspector.ts: Developer debugging tools - JSDoc examples in documentation Closes #363 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * Address review: Fix minor formatting issues in logging - Remove unused _isDev variable in logger.ts (YAGNI principle) - Remove leading spaces from log messages in shared-node-store.svelte.ts (18 occurrences fixed for consistent output formatting) Addresses reviewer recommendations from PR #733 code review. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * Add logging standards to code quality documentation Added comprehensive logging section to code-quality.md: - Zero console.log policy with exemptions for tests and DeveloperInspector - Logger utility usage examples with createLogger() - Log levels table with production visibility guidance - Environment behavior (production vs development vs test) - Logger features (timing, grouping) - Migration guide from raw console.* calls Addresses "Nice to Have" acceptance criterion from issue #363: "Logging documentation added to development guide" 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * Add logging policy and link to code quality standards in CLAUDE.md - Added link to docs/architecture/development/standards/code-quality.md - Added Logging Policy section with quick reference to Logger utility - Ensures AI agents are aware of logging standards 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
1 parent dab7d47 commit fe09c33

51 files changed

Lines changed: 706 additions & 1144 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CLAUDE.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,9 @@ IMPORTANT SUB-AGENT INSTRUCTIONS:
460460
461461
### 6. Development Standards
462462
463+
> **📖 Complete Standards Documentation:**
464+
> - [`/docs/architecture/development/standards/code-quality.md`](docs/architecture/development/standards/code-quality.md) - Full code quality standards including logging
465+
463466
**Code Quality:**
464467
- Follow Rust formatting standards (rustfmt)
465468
- Use TypeScript for frontend type safety
@@ -472,6 +475,13 @@ IMPORTANT SUB-AGENT INSTRUCTIONS:
472475
- Use proper TypeScript types instead of `any`
473476
- Follow Svelte best practices and avoid unsafe patterns like `{@html}`
474477
478+
**Logging Policy:**
479+
- **NO raw `console.log/debug/info/warn/error`** in production code - Use Logger utility
480+
- Import: `import { createLogger } from '$lib/utils/logger';`
481+
- Create logger: `const log = createLogger('ServiceName');`
482+
- Use: `log.debug()`, `log.info()`, `log.warn()`, `log.error()`
483+
- Test files and DeveloperInspector are exempt
484+
475485
**Runtime and Package Manager:**
476486
- **MANDATORY: Bun-only development** - Node.js not required
477487
- All scripts use `bunx` for consistent Bun runtime execution

‎docs/architecture/development/standards/code-quality.md‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,86 @@ function handleData(data: DataType) {
156156
<MarkdownRenderer content={safeContent} />
157157
```
158158

159+
## 🔊 Logging Standards
160+
161+
### ZERO CONSOLE.LOG POLICY
162+
163+
**FUNDAMENTAL RULES:**
164+
- [ ] **NO raw `console.log/debug/info` in production code** - Use the Logger utility instead
165+
- [ ] **NO raw `console.warn/error` in production code** - Use the Logger utility instead
166+
- [ ] **Test files are exempt** - `console.log` is acceptable in test output
167+
- [ ] **DeveloperInspector is exempt** - Intentionally uses raw console for dev tools
168+
169+
### Logger Utility Usage
170+
171+
**Location:** `src/lib/utils/logger.ts`
172+
173+
```typescript
174+
// ✅ CORRECT - Use createLogger with service/component name
175+
import { createLogger } from '$lib/utils/logger';
176+
177+
const log = createLogger('MyService');
178+
179+
log.debug('Operation started', { data }); // Hidden in production
180+
log.info('User action', { action }); // Hidden in production
181+
log.warn('Potential issue', { context }); // Visible in production
182+
log.error('Operation failed', error); // Visible in production
183+
```
184+
185+
```typescript
186+
// ❌ WRONG - Raw console calls
187+
console.log('[MyService] Operation started', data);
188+
console.error('[MyService] Operation failed:', error);
189+
```
190+
191+
### Log Levels
192+
193+
| Level | When to Use | Production Visibility |
194+
|-------|-------------|----------------------|
195+
| `debug` | Detailed debugging info, state changes | Hidden |
196+
| `info` | Operational info, user actions | Hidden |
197+
| `warn` | Warnings that don't block operation | **Visible** |
198+
| `error` | Actual errors, failures | **Visible** |
199+
200+
### Environment Behavior
201+
202+
- **Production**: Only `warn` and `error` logs are shown (clean console)
203+
- **Development**: All log levels shown (`debug` and above)
204+
- **Test**: All logs disabled (improves test performance)
205+
206+
### Logger Features
207+
208+
```typescript
209+
const log = createLogger('NavigationService');
210+
211+
// Basic logging with optional data
212+
log.debug('Resolving node', { nodeId });
213+
log.error('Failed to navigate', error);
214+
215+
// Timing operations
216+
const done = log.time('Loading data');
217+
await loadData();
218+
done(); // Logs: [NavigationService] Loading data: 123.45ms
219+
220+
// Grouping related logs
221+
log.group('Complex operation');
222+
log.debug('Step 1');
223+
log.debug('Step 2');
224+
log.groupEnd();
225+
```
226+
227+
### Migration from console.*
228+
229+
When you encounter raw `console.*` calls:
230+
231+
1. Import the logger: `import { createLogger } from '$lib/utils/logger';`
232+
2. Create a logger instance: `const log = createLogger('ComponentName');`
233+
3. Replace calls:
234+
- `console.log` → `log.debug` or `log.info`
235+
- `console.warn` → `log.warn`
236+
- `console.error` → `log.error`
237+
4. Remove prefixes from messages (Logger adds `[ComponentName]` automatically)
238+
159239
## Quality Tools Configuration
160240

161241
**ESLint Configuration:**

‎packages/desktop-app/src/lib/components/autocomplete-modal.svelte‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,9 @@
7171
import Separator from '$lib/components/ui/separator/separator.svelte';
7272
import Icon, { type IconName } from '$lib/design/icons';
7373
import type { Node } from '$lib/types';
74+
import { createLogger } from '$lib/utils/logger';
75+
76+
const log = createLogger('AutocompleteModal');
7477
7578
// ============================================================================
7679
// Component Props & Types
@@ -188,7 +191,7 @@
188191
hasMore = result.hasMore;
189192
selectedIndex = 0;
190193
} catch (error) {
191-
console.error('AutocompleteModal: Search failed', error);
194+
log.error('Search failed', error);
192195
searchError = 'Search failed. Please try again.';
193196
searchResults = [];
194197
} finally {
@@ -228,7 +231,7 @@
228231
searchResults = suggestions;
229232
selectedIndex = 0;
230233
} catch (error) {
231-
console.error('AutocompleteModal: Failed to load default results', error);
234+
log.error('Failed to load default results', error);
232235
searchResults = [];
233236
} finally {
234237
isLoading = false;
@@ -262,10 +265,10 @@
262265
dispatch('nodeSelect', { node });
263266
closeModal();
264267
} else {
265-
console.error('AutocompleteModal: Failed to resolve selected node', suggestion.nodeId);
268+
log.error('Failed to resolve selected node', suggestion.nodeId);
266269
}
267270
} catch (error) {
268-
console.error('AutocompleteModal: Error selecting node', error);
271+
log.error('Error selecting node', error);
269272
}
270273
}
271274

‎packages/desktop-app/src/lib/components/layout/app-shell.svelte‎

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@
1717
import type { Node } from '$lib/types';
1818
import { loadPersistedState } from '$lib/stores/navigation';
1919
import { TabPersistenceService } from '$lib/services/tab-persistence-service';
20+
import { createLogger } from '$lib/utils/logger';
2021
21-
// Constants
22-
const LOG_PREFIX = '[AppShell]';
22+
// Logger instance for AppShell component
23+
const log = createLogger('AppShell');
2324
2425
/**
2526
* Sets up MCP event listeners for real-time UI updates
@@ -33,7 +34,7 @@
3334
function setupMCPListeners(sharedNodeStore: SharedNodeStore): () => Promise<void> {
3435
// Listen for node creation events from MCP
3536
const unlistenNodeCreated = listen<{ node: Node }>(MCP_EVENTS.NODE_CREATED, (event) => {
36-
console.log(`${LOG_PREFIX} [MCP] Node created:`, event.payload.node.id);
37+
log.debug('[MCP] Node created:', event.payload.node.id);
3738
sharedNodeStore.setNode(
3839
event.payload.node,
3940
{ type: 'mcp-server' },
@@ -45,30 +46,26 @@
4546
const unlistenNodeUpdated = listen<{ node_id: string }>(
4647
MCP_EVENTS.NODE_UPDATED,
4748
async (event) => {
48-
console.log(`${LOG_PREFIX} [MCP] Node updated:`, event.payload.node_id);
49+
log.debug('[MCP] Node updated:', event.payload.node_id);
4950
try {
5051
const node = await invoke<Node>('get_node', { id: event.payload.node_id });
5152
if (node) {
5253
sharedNodeStore.setNode(node, { type: 'mcp-server' }, false);
5354
} else {
54-
console.warn(
55-
`${LOG_PREFIX} [MCP] Node not found after update event:`,
55+
log.warn(
56+
'[MCP] Node not found after update event:',
5657
event.payload.node_id
5758
);
5859
}
5960
} catch (error) {
60-
console.error(
61-
`${LOG_PREFIX} [MCP] Failed to fetch node after update event:`,
62-
event.payload.node_id,
63-
error
64-
);
61+
log.error(`[MCP] Failed to fetch node after update event: ${event.payload.node_id}`, error);
6562
}
6663
}
6764
);
6865
6966
// Listen for node deletion events from MCP
7067
const unlistenNodeDeleted = listen<{ node_id: string }>(MCP_EVENTS.NODE_DELETED, (event) => {
71-
console.log(`${LOG_PREFIX} [MCP] Node deleted:`, event.payload.node_id);
68+
log.debug('[MCP] Node deleted:', event.payload.node_id);
7269
sharedNodeStore.deleteNode(
7370
event.payload.node_id,
7471
{ type: 'mcp-server' },
@@ -93,17 +90,17 @@
9390
// Load persisted tab state from storage
9491
const stateLoaded = loadPersistedState();
9592
if (stateLoaded) {
96-
console.log(`${LOG_PREFIX} Persisted tab state loaded successfully`);
93+
log.debug('Persisted tab state loaded successfully');
9794
} else {
98-
console.log(`${LOG_PREFIX} No persisted tab state found, using default state`);
95+
log.debug('No persisted tab state found, using default state');
9996
}
10097
10198
// Load persisted layout state (sidebar collapsed/expanded) from storage
10299
const layoutStateLoaded = loadPersistedLayoutState();
103100
if (layoutStateLoaded) {
104-
console.log(`${LOG_PREFIX} Persisted layout state loaded successfully`);
101+
log.debug('Persisted layout state loaded successfully');
105102
} else {
106-
console.log(`${LOG_PREFIX} No persisted layout state found, using default state`);
103+
log.debug('No persisted layout state found, using default state');
107104
}
108105
109106
// Initialize the unified plugin registry with core plugins
@@ -127,7 +124,7 @@
127124
// Browser mode: Initialize SSE-based sync for real-time updates
128125
// This connects to dev-proxy's /api/events endpoint for external change notifications
129126
browserSyncService.initialize().catch((error) => {
130-
console.error(`${LOG_PREFIX} Failed to initialize browser sync service:`, error);
127+
log.error('Failed to initialize browser sync service:', error);
131128
});
132129
}
133130
@@ -167,7 +164,7 @@
167164
// Validate node ID is not empty
168165
// NavigationService will handle resolution (UUIDs, date nodes, etc.)
169166
if (!nodeId || nodeId.trim() === '') {
170-
console.error(`${LOG_PREFIX} Empty node ID in link`);
167+
log.error('Empty node ID in link');
171168
return;
172169
}
173170

‎packages/desktop-app/src/lib/components/layout/pane-content.svelte‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
import { tabState, updateTabTitle, updateTabContent } from '$lib/stores/navigation.js';
55
import { pluginRegistry } from '$lib/plugins/plugin-registry';
66
import type { Pane } from '$lib/stores/navigation.js';
7+
import { createLogger } from '$lib/utils/logger';
8+
9+
const log = createLogger('PaneContent');
710
811
// ✅ Receive the PANE as a prop - each pane instance gets its own pane object
912
let { pane }: { pane: Pane } = $props();
@@ -35,7 +38,7 @@
3538
}
3639
} catch (error) {
3740
const errorMessage = error instanceof Error ? error.message : 'Unknown error loading viewer';
38-
console.error(`[PaneContent] Failed to load viewer for ${nodeType}:`, error);
41+
log.error(`Failed to load viewer for ${nodeType}:`, error);
3942
viewerLoadErrors = new Map(viewerLoadErrors.set(nodeType, errorMessage));
4043
}
4144
}

‎packages/desktop-app/src/lib/components/layout/tab-system.svelte‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@
4444
import type { Tab, Pane } from '$lib/stores/navigation.js';
4545
import type { Snippet } from 'svelte';
4646
import { draggable, droppable, type DragDropState } from '@thisux/sveltednd';
47+
import { createLogger } from '$lib/utils/logger';
48+
49+
// Logger instance for TabSystem component
50+
const log = createLogger('TabSystem');
4751
4852
// Props - when used inside PaneManager
4953
let {
@@ -176,7 +180,7 @@
176180
177181
// Early validation: check for required state
178182
if (!draggedItem || !targetContainer || !sourceContainer) {
179-
console.warn('[TabSystem] Invalid drop operation: missing required state', {
183+
log.warn('Invalid drop operation: missing required state', {
180184
hasDraggedItem: !!draggedItem,
181185
hasTargetContainer: !!targetContainer,
182186
hasSourceContainer: !!sourceContainer
@@ -190,7 +194,7 @@
190194
const targetIndex = parseInt(targetContainer.replace('tab-', ''));
191195
192196
if (isNaN(sourceIndex) || isNaN(targetIndex)) {
193-
console.error('[TabSystem] Invalid drop operation: could not parse container indices', {
197+
log.error('Invalid drop operation: could not parse container indices', {
194198
sourceContainer,
195199
targetContainer,
196200
sourceIndex,
@@ -211,7 +215,7 @@
211215
const targetPaneExists = $tabState.panes.some((p) => p.id === currentPaneId);
212216
213217
if (!sourcePaneExists || !targetPaneExists) {
214-
console.error('[TabSystem] Invalid drop operation: pane not found', {
218+
log.error('Invalid drop operation: pane not found', {
215219
sourcePaneId,
216220
targetPaneId: currentPaneId,
217221
sourcePaneExists,
@@ -258,7 +262,7 @@
258262
moveTabBetweenPanes(tabId, sourcePaneId, currentPaneId, targetIndex);
259263
}
260264
} catch (error) {
261-
console.error('[TabSystem] Drop operation failed:', error);
265+
log.error('Drop operation failed:', error);
262266
// Could show user-facing toast notification here in the future
263267
} finally {
264268
// Always clear drag-over state

‎packages/desktop-app/src/lib/components/property-forms/schema-property-form.svelte‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@
2828
import { type SchemaNode, type SchemaField, type EnumValue, isSchemaNode } from '$lib/types/schema-node';
2929
import type { Node } from '$lib/types';
3030
import { parseDate, type DateValue } from '@internationalized/date';
31+
import { createLogger } from '$lib/utils/logger';
32+
33+
// Logger instance for SchemaPropertyForm component
34+
const log = createLogger('SchemaPropertyForm');
3135
3236
// Props
3337
let {
@@ -98,7 +102,7 @@
98102
schema = null;
99103
}
100104
} catch (error) {
101-
console.error('[SchemaPropertyForm] Failed to load schema:', error);
105+
log.error('Failed to load schema:', error);
102106
schemaError = error instanceof Error ? error.message : 'Failed to load schema';
103107
schema = null;
104108
}

‎packages/desktop-app/src/lib/components/property-forms/task-schema-form.svelte‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@
2626
import type { TaskNode, TaskStatus } from '$lib/types/task-node';
2727
import { nodeToTaskNode } from '$lib/types/task-node';
2828
import { parseDate, type DateValue } from '@internationalized/date';
29+
import { createLogger } from '$lib/utils/logger';
30+
31+
// Logger instance for TaskSchemaForm component
32+
const log = createLogger('TaskSchemaForm');
2933
3034
// Props - only nodeId needed since we know it's a task
3135
let { nodeId }: { nodeId: string } = $props();
@@ -71,7 +75,7 @@
7175
schema = schemaNode;
7276
}
7377
} catch (error) {
74-
console.error('[TaskSchemaForm] Failed to load schema:', error);
78+
log.error('Failed to load schema:', error);
7579
}
7680
}
7781
loadSchema();

‎packages/desktop-app/src/lib/components/references/index.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
import BaseNodeReference from '../base-node-reference.svelte';
99
import { pluginRegistry } from '$lib/plugins/index';
1010
import type { SvelteComponent } from 'svelte';
11+
import { createLogger } from '$lib/utils/logger';
12+
13+
const log = createLogger('ReferenceRegistry');
1114

1215
// Component type for Svelte components
1316
export type NodeReferenceComponent = new (...args: unknown[]) => SvelteComponent;
@@ -36,8 +39,8 @@ export const NODE_REFERENCE_COMPONENTS: Record<string, NodeReferenceComponent> =
3639
},
3740

3841
set(_target, _prop: string, _value: NodeReferenceComponent) {
39-
console.warn(
40-
`NODE_REFERENCE_COMPONENTS assignment is deprecated. Use the unified plugin system instead.`
42+
log.warn(
43+
'NODE_REFERENCE_COMPONENTS assignment is deprecated. Use the unified plugin system instead.'
4144
);
4245
// We don't support the old API anymore
4346
return false;
@@ -77,8 +80,8 @@ export function registerNodeReferenceComponent(
7780
_nodeType: string,
7881
_component: NodeReferenceComponent
7982
): void {
80-
console.warn(
81-
`registerNodeReferenceComponent() is deprecated. Use the unified plugin system instead.`
83+
log.warn(
84+
'registerNodeReferenceComponent() is deprecated. Use the unified plugin system instead.'
8285
);
8386
// This is a breaking change - we don't support the old API
8487
throw new Error(

0 commit comments

Comments
 (0)