Skip to content

Commit 16559da

Browse files
malibioclaude
andcommitted
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]>
1 parent 910954a commit 16559da

7 files changed

Lines changed: 186 additions & 104 deletions

File tree

‎packages/desktop-app/src/lib/plugins/schema-plugin-loader.ts‎

Lines changed: 17 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ import type { PluginDefinition } from './types';
4242
import { pluginRegistry } from './plugin-registry';
4343
import { backendAdapter } from '$lib/services/backend-adapter';
4444
import { type SchemaNode, isSchemaNode } from '$lib/types/schema-node';
45+
import { createLogger } from '$lib/utils/logger';
46+
47+
const log = createLogger('SchemaPluginLoader');
4548

4649
/**
4750
* Plugin priority constants
@@ -165,38 +168,29 @@ export async function registerSchemaPlugin(schemaId: string): Promise<void> {
165168

166169
// Verify it's a schema node
167170
if (!isSchemaNode(node)) {
168-
console.warn(`[SchemaPluginLoader] Node ${schemaId} is not a schema node`);
171+
log.warn(`Node ${schemaId} is not a schema node`);
169172
return;
170173
}
171174

172175
// Don't register core types (already registered in core-plugins.ts)
173176
// Access typed field directly (no helper needed)
174177
if (node.isCore) {
175-
console.debug(
176-
`[SchemaPluginLoader] Skipping core type registration: ${schemaId}`
177-
);
178+
log.debug(`Skipping core type registration: ${schemaId}`);
178179
return;
179180
}
180181

181182
// Check if already registered (idempotent)
182183
if (pluginRegistry.hasPlugin(schemaId)) {
183-
console.debug(
184-
`[SchemaPluginLoader] Plugin already registered: ${schemaId}`
185-
);
184+
log.debug(`Plugin already registered: ${schemaId}`);
186185
return;
187186
}
188187

189188
const plugin = createPluginFromSchema(node);
190189
pluginRegistry.register(plugin);
191190

192-
console.log(
193-
`[SchemaPluginLoader] Registered plugin for custom entity: ${schemaId}`
194-
);
191+
log.info(`Registered plugin for custom entity: ${schemaId}`);
195192
} catch (error) {
196-
console.error(
197-
`[SchemaPluginLoader] Failed to register schema plugin: ${schemaId}`,
198-
error
199-
);
193+
log.error(`Failed to register schema plugin: ${schemaId}`, error);
200194
throw error;
201195
}
202196
}
@@ -218,14 +212,12 @@ export async function registerSchemaPlugin(schemaId: string): Promise<void> {
218212
*/
219213
export function unregisterSchemaPlugin(schemaId: string): void {
220214
if (!pluginRegistry.hasPlugin(schemaId)) {
221-
console.warn(
222-
`[SchemaPluginLoader] Attempted to unregister non-existent plugin: ${schemaId}`
223-
);
215+
log.warn(`Attempted to unregister non-existent plugin: ${schemaId}`);
224216
return;
225217
}
226218

227219
pluginRegistry.unregister(schemaId);
228-
console.log(`[SchemaPluginLoader] Unregistered plugin: ${schemaId}`);
220+
log.info(`Unregistered plugin: ${schemaId}`);
229221
}
230222

231223
/**
@@ -248,7 +240,7 @@ export function unregisterSchemaPlugin(schemaId: string): void {
248240
*/
249241
async function _registerExistingSchemas(): Promise<void> {
250242
try {
251-
console.log('[SchemaPluginLoader] Registering existing custom entity schemas...');
243+
log.debug('Registering existing custom entity schemas...');
252244

253245
const nodes = await backendAdapter.getAllSchemas();
254246

@@ -263,14 +255,9 @@ async function _registerExistingSchemas(): Promise<void> {
263255
customSchemas.map((node) => registerSchemaPlugin(node.id))
264256
);
265257

266-
console.log(
267-
`[SchemaPluginLoader] Registered ${customSchemas.length} custom entity schemas`
268-
);
258+
log.info(`Registered ${customSchemas.length} custom entity schemas`);
269259
} catch (error) {
270-
console.error(
271-
'[SchemaPluginLoader] Failed to register existing schemas:',
272-
error
273-
);
260+
log.error('Failed to register existing schemas:', error);
274261
throw error;
275262
}
276263
}
@@ -310,7 +297,7 @@ export interface InitializationResult {
310297
*/
311298
export async function initializeSchemaPluginSystem(): Promise<InitializationResult> {
312299
try {
313-
console.log('[SchemaPluginLoader] Initializing schema plugin system...');
300+
log.debug('Initializing schema plugin system...');
314301

315302
// Register existing custom entity schemas on startup
316303
const nodes = await backendAdapter.getAllSchemas();
@@ -337,8 +324,8 @@ export async function initializeSchemaPluginSystem(): Promise<InitializationResu
337324
// unregisterSchemaPlugin(event.payload.schema_id);
338325
// });
339326

340-
console.log(
341-
`[SchemaPluginLoader] Schema plugin system initialized (${customSchemas.length} custom entities registered)`
327+
log.info(
328+
`Schema plugin system initialized (${customSchemas.length} custom entities registered)`
342329
);
343330

344331
return {
@@ -347,7 +334,7 @@ export async function initializeSchemaPluginSystem(): Promise<InitializationResu
347334
};
348335
} catch (error) {
349336
const errorMessage = error instanceof Error ? error.message : String(error);
350-
console.error('[SchemaPluginLoader] Failed to initialize:', error);
337+
log.error('Failed to initialize:', error);
351338

352339
return {
353340
success: false,

‎packages/desktop-app/src/lib/services/app-initialization.ts‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@
55
* any components try to use Tauri commands.
66
*/
77

8+
import { createLogger } from '$lib/utils/logger';
9+
10+
const log = createLogger('AppInit');
11+
812
// Tauri API types
913
interface TauriCore {
1014
invoke: (command: string, ...args: unknown[]) => Promise<unknown>;
@@ -51,7 +55,7 @@ async function waitForTauriReady(): Promise<void> {
5155
typeof window.__TAURI__ !== 'undefined' &&
5256
typeof window.__TAURI__.core?.invoke === 'function'
5357
) {
54-
console.log('[App Init] Tauri API ready after', attempts * delayMs, 'ms');
58+
log.debug(`Tauri API ready after ${attempts * delayMs}ms`);
5559
return;
5660
}
5761

@@ -60,7 +64,7 @@ async function waitForTauriReady(): Promise<void> {
6064
typeof window !== 'undefined' &&
6165
typeof window.__TAURI__?.invoke === 'function'
6266
) {
63-
console.log('[App Init] Tauri API ready (legacy) after', attempts * delayMs, 'ms');
67+
log.debug(`Tauri API ready (legacy) after ${attempts * delayMs}ms`);
6468
return;
6569
}
6670

@@ -74,7 +78,7 @@ async function waitForTauriReady(): Promise<void> {
7478
const hasInvokeCore = hasTauri && typeof window.__TAURI__?.core?.invoke === 'function';
7579
const hasInvokeLegacy = hasTauri && typeof window.__TAURI__?.invoke === 'function';
7680

77-
console.error('[App Init] Tauri API check results:', {
81+
log.error('Tauri API check results:', {
7882
isWindow,
7983
hasTauri,
8084
hasInvokeCore,
@@ -104,7 +108,7 @@ export async function initializeApp(): Promise<void> {
104108

105109
// Skip Tauri initialization in browser mode (using HTTP dev-proxy)
106110
if (!isTauriEnvironment()) {
107-
console.log('[App Init] Running in browser mode, skipping Tauri initialization');
111+
log.debug('Running in browser mode, skipping Tauri initialization');
108112
return;
109113
}
110114

@@ -121,18 +125,18 @@ export async function initializeApp(): Promise<void> {
121125
throw new Error('Tauri invoke function not available');
122126
}
123127
await invoke('initialize_database');
124-
console.log('[App Init] Database initialized');
128+
log.info('Database initialized');
125129
} catch (error: unknown) {
126130
// Check if already initialized (this is expected on subsequent calls)
127131
const errorMsg = error instanceof Error ? error.message : String(error);
128132
if (errorMsg.includes('already initialized')) {
129-
console.log('[App Init] Database already initialized');
133+
log.debug('Database already initialized');
130134
} else {
131-
console.warn('[App Init] Database initialization warning:', error);
135+
log.warn('Database initialization warning:', error);
132136
}
133137
}
134138
} catch (error: unknown) {
135-
console.error('[App Init] Critical initialization error:', error);
139+
log.error('Critical initialization error:', error);
136140
throw error;
137141
}
138142
}

‎packages/desktop-app/src/lib/services/browser-sync-service.ts‎

Lines changed: 28 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ import type { SseEvent } from '$lib/types/sse-events';
2626
import type { Node } from '$lib/types/node';
2727
import { nodeToTaskNode } from '$lib/types/task-node';
2828
import { backendAdapter } from './backend-adapter';
29+
import { createLogger } from '$lib/utils/logger';
30+
31+
const log = createLogger('BrowserSyncService');
2932

3033
/**
3134
* Connection state for the SSE client
@@ -113,11 +116,11 @@ class BrowserSyncService {
113116
async initialize(): Promise<void> {
114117
// Only run in browser mode (not Tauri)
115118
if (!this.isBrowserMode()) {
116-
console.log('[BrowserSyncService] Skipping - running in Tauri mode');
119+
log.debug('Skipping - running in Tauri mode');
117120
return;
118121
}
119122

120-
console.log('[BrowserSyncService] Initializing SSE connection for browser mode');
123+
log.debug('Initializing SSE connection for browser mode');
121124
this.connect();
122125
}
123126

@@ -137,7 +140,7 @@ class BrowserSyncService {
137140
*/
138141
private connect(): void {
139142
if (this.connectionState === 'connecting' || this.connectionState === 'connected') {
140-
console.log('[BrowserSyncService] Already connected or connecting');
143+
log.debug('Already connected or connecting');
141144
return;
142145
}
143146

@@ -146,13 +149,13 @@ class BrowserSyncService {
146149
// No clientId needed (Issue #715) - dev-proxy handles filtering server-side
147150
const sseUrl = this.sseEndpoint;
148151

149-
console.log('[BrowserSyncService] Connecting to SSE endpoint:', sseUrl);
152+
log.debug('Connecting to SSE endpoint:', sseUrl);
150153

151154
try {
152155
this.eventSource = new EventSource(sseUrl);
153156

154157
this.eventSource.onopen = () => {
155-
console.log('[BrowserSyncService] SSE connection established');
158+
log.info('SSE connection established');
156159
this.connectionState = 'connected';
157160
this.reconnectAttempts = 0;
158161
};
@@ -162,14 +165,14 @@ class BrowserSyncService {
162165
};
163166

164167
this.eventSource.onerror = (error) => {
165-
console.warn('[BrowserSyncService] SSE connection error:', error);
168+
log.warn('SSE connection error:', error);
166169
this.connectionState = 'disconnected';
167170
this.eventSource?.close();
168171
this.eventSource = null;
169172
this.scheduleReconnect();
170173
};
171174
} catch (error) {
172-
console.error('[BrowserSyncService] Failed to create EventSource:', error);
175+
log.error('Failed to create EventSource:', error);
173176
this.connectionState = 'disconnected';
174177
this.scheduleReconnect();
175178
}
@@ -181,10 +184,10 @@ class BrowserSyncService {
181184
private handleMessage(event: MessageEvent): void {
182185
try {
183186
const data = JSON.parse(event.data) as SseEvent;
184-
console.log('[BrowserSyncService] Received event:', data.type);
187+
log.debug('Received event:', data.type);
185188
this.handleEvent(data);
186189
} catch (error) {
187-
console.error('[BrowserSyncService] Failed to parse SSE event:', error, event.data);
190+
log.error('Failed to parse SSE event:', { error, data: event.data });
188191
}
189192
}
190193

@@ -222,32 +225,32 @@ class BrowserSyncService {
222225

223226
switch (event.type) {
224227
case 'nodeCreated': {
225-
console.log('[BrowserSyncService] Node created:', event.nodeId);
228+
log.debug('Node created:', event.nodeId);
226229
// Issue #724: Fetch full node data only if we need to display it
227230
// For now, always fetch since the node might be in the current view
228231
this.fetchAndUpdateNode(event.nodeId, 'nodeCreated');
229232
break;
230233
}
231234

232235
case 'nodeUpdated': {
233-
console.log('[BrowserSyncService] Node updated:', event.nodeId);
236+
log.debug('Node updated:', event.nodeId);
234237
// Issue #724: Only fetch if node is already in the store (visible to user)
235238
// This avoids unnecessary API calls for nodes not in the current view
236239
if (sharedNodeStore.hasNode(event.nodeId)) {
237240
this.fetchAndUpdateNode(event.nodeId, 'nodeUpdated');
238241
} else {
239-
console.log('[BrowserSyncService] Node not in store, skipping fetch:', event.nodeId);
242+
log.debug('Node not in store, skipping fetch:', event.nodeId);
240243
}
241244
break;
242245
}
243246

244247
case 'nodeDeleted':
245-
console.log('[BrowserSyncService] Node deleted:', event.nodeId);
248+
log.debug('Node deleted:', event.nodeId);
246249
sharedNodeStore.deleteNode(event.nodeId, { type: 'database', reason: 'sse-sync' }, true);
247250
break;
248251

249252
case 'edgeCreated':
250-
console.log('[BrowserSyncService] Edge created:', event.parentId, '->', event.childId);
253+
log.debug('Edge created:', { from: event.parentId, to: event.childId });
251254
// Update ReactiveStructureTree with new edge
252255
// Note: structureTree.addChild expects HierarchyRelationship format
253256
// IMPORTANT: Check if edge already exists (added optimistically by createNode)
@@ -262,16 +265,13 @@ class BrowserSyncService {
262265
order: Date.now() // Use timestamp as order (will be sorted properly on next load)
263266
});
264267
} else {
265-
console.log(
266-
'[BrowserSyncService] Edge already exists (optimistic), skipping:',
267-
event.childId
268-
);
268+
log.debug('Edge already exists (optimistic), skipping:', event.childId);
269269
}
270270
}
271271
break;
272272

273273
case 'edgeDeleted':
274-
console.log('[BrowserSyncService] Edge deleted:', event.parentId, '->', event.childId);
274+
log.debug('Edge deleted:', { from: event.parentId, to: event.childId });
275275
// Update ReactiveStructureTree by removing edge
276276
if (structureTree) {
277277
structureTree.removeChild({
@@ -283,7 +283,7 @@ class BrowserSyncService {
283283
break;
284284

285285
default:
286-
console.warn('[BrowserSyncService] Unknown event type:', (event as SseEvent).type);
286+
log.warn('Unknown event type:', (event as SseEvent).type);
287287
}
288288
}
289289

@@ -301,12 +301,12 @@ class BrowserSyncService {
301301
const normalizedNode = this.normalizeNodeData(node);
302302
// Use database source with sse-sync reason to indicate external change via SSE
303303
sharedNodeStore.setNode(normalizedNode, { type: 'database', reason: 'sse-sync' }, true);
304-
console.log(`[BrowserSyncService] ${eventType}: updated store for node`, nodeId);
304+
log.debug(`${eventType}: updated store for node`, nodeId);
305305
} else {
306-
console.warn(`[BrowserSyncService] ${eventType}: node not found`, nodeId);
306+
log.warn(`${eventType}: node not found`, nodeId);
307307
}
308308
} catch (error) {
309-
console.error(`[BrowserSyncService] ${eventType}: failed to fetch node`, nodeId, error);
309+
log.error(`${eventType}: failed to fetch node`, { nodeId, error });
310310
}
311311
}
312312

@@ -315,19 +315,15 @@ class BrowserSyncService {
315315
*/
316316
private scheduleReconnect(): void {
317317
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
318-
console.error(
319-
'[BrowserSyncService] Max reconnect attempts reached. Real-time sync disabled.'
320-
);
321-
console.error(
322-
'[BrowserSyncService] Please check if dev-proxy is running (bun run dev:browser)'
323-
);
318+
log.error('Max reconnect attempts reached. Real-time sync disabled.');
319+
log.error('Please check if dev-proxy is running (bun run dev:browser)');
324320
return;
325321
}
326322

327323
this.reconnectAttempts++;
328324
const delay = this.baseReconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
329-
console.log(
330-
`[BrowserSyncService] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`
325+
log.info(
326+
`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`
331327
);
332328

333329
this.reconnectTimeout = setTimeout(() => {
@@ -356,7 +352,7 @@ class BrowserSyncService {
356352
* Should be called when the app is unmounted to clean up resources.
357353
*/
358354
destroy(): void {
359-
console.log('[BrowserSyncService] Destroying service');
355+
log.debug('Destroying service');
360356

361357
if (this.reconnectTimeout) {
362358
clearTimeout(this.reconnectTimeout);

0 commit comments

Comments
 (0)