Skip to content

Commit 7e9fae2

Browse files
author
Lasim
committed
chore(backend): improve logging structure for error handling
1 parent 2aef844 commit 7e9fae2

File tree

16 files changed

+50
-50
lines changed

16 files changed

+50
-50
lines changed

services/backend/src/plugin-system/plugin-manager.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ export class PluginManager {
118118
this.logger?.debug(`Trying to import as module: ${pluginPath}`);
119119
pluginPackage = await import(pluginPath);
120120
} catch (err) {
121-
this.logger?.debug(`Module import failed, trying require: ${pluginPath}`, err);
121+
this.logger?.debug({ error: err }, `Module import failed, trying require: ${pluginPath}`);
122122
// Using dynamic import with a constructed path to avoid require()
123123
// This is a workaround for the ESLint rule @typescript-eslint/no-require-imports
124124
pluginPackage = await import(`${pluginPath}`);
@@ -153,7 +153,7 @@ export class PluginManager {
153153
if (error instanceof PluginDuplicateError) {
154154
throw error;
155155
}
156-
this.logger?.error(`Error loading plugin from ${pluginPath}:`, error);
156+
this.logger?.error({ error }, `Error loading plugin from ${pluginPath}:`);
157157
throw new PluginLoadError(path.basename(pluginPath), error);
158158
}
159159
}
@@ -210,7 +210,7 @@ export class PluginManager {
210210
this.logger?.debug(`Found main file: ${mainPath}`);
211211
await this.loadPlugin(mainPath);
212212
} catch (accessErr) {
213-
this.logger?.debug(`Main file not found: ${mainPath}, error:`, accessErr);
213+
this.logger?.debug({ error: accessErr }, `Main file not found: ${mainPath}, error:`);
214214

215215
// If preferred file not found, try alternative
216216
const altExtension = pluginExtension === 'ts' ? 'js' : 'ts';
@@ -236,7 +236,7 @@ export class PluginManager {
236236
await this.loadPlugin(pluginPath);
237237
}
238238
} catch (error) {
239-
this.logger?.error(`Error discovering plugins at ${pluginPath}:`, error);
239+
this.logger?.error({ error }, `Error discovering plugins at ${pluginPath}:`);
240240
}
241241
}
242242

@@ -331,7 +331,7 @@ export class PluginManager {
331331
this.logger?.warn(`Global setting group ID '${group.id}' already exists (Existing Name: "${existingGroup.name}"). Plugin's attempt to define a group with this ID (Plugin's proposed Name: "${group.name}") will use the existing group. Plugin-specific metadata for this group ID (name, description, icon, sort_order) is ignored.`);
332332
}
333333
} catch (error) {
334-
this.logger?.error(`Error processing plugin-defined group '${group.id}' (Plugin's proposed Name: "${group.name}"):`, error);
334+
this.logger?.error({ error }, `Error processing plugin-defined group '${group.id}' (Plugin's proposed Name: "${group.name}"):`);
335335
}
336336
}
337337

@@ -342,7 +342,7 @@ export class PluginManager {
342342
const coreSettings = await GlobalSettingsService.getAll();
343343
coreSettings.forEach(cs => initializedKeys.add(cs.key));
344344
} catch (error) {
345-
this.logger?.error('Failed to get all core settings for precedence check:', error);
345+
this.logger?.error({ error }, 'Failed to get all core settings for precedence check:');
346346
// If this fails, we might risk overwriting, but proceed with caution.
347347
}
348348

@@ -362,7 +362,7 @@ export class PluginManager {
362362
initializedKeys.add(definition.key); // Add to set after successful initialization
363363
this.logger?.info(`Initialized global setting '${definition.key}' from plugin '${pluginId}'.`);
364364
} catch (error) {
365-
this.logger?.error(`Failed to initialize global setting '${definition.key}' from plugin '${pluginId}':`, error);
365+
this.logger?.error({ error }, `Failed to initialize global setting '${definition.key}' from plugin '${pluginId}':`);
366366
}
367367
}
368368
this.logger?.info('Plugin global settings initialization complete.');
@@ -402,7 +402,7 @@ export class PluginManager {
402402
} catch (error) {
403403
// Log individual plugin initialization errors but continue with others.
404404
const typedError = error as Error;
405-
this.logger?.error(`Failed to initialize plugin ${plugin.meta.id}: ${typedError.message}`, typedError.stack);
405+
this.logger?.error({ error: typedError, stack: typedError.stack }, `Failed to initialize plugin ${plugin.meta.id}: ${typedError.message}`);
406406
// Optionally, re-throw: throw new PluginInitializeError(plugin.meta.id, error);
407407
}
408408
}
@@ -440,7 +440,7 @@ export class PluginManager {
440440
}
441441
} catch (error) {
442442
const typedError = error as Error;
443-
this.logger?.error(`Failed to re-initialize plugin ${plugin.meta.id}: ${typedError.message}`, typedError.stack);
443+
this.logger?.error({ error: typedError, stack: typedError.stack }, `Failed to re-initialize plugin ${plugin.meta.id}: ${typedError.message}`);
444444
// Continue with other plugins even if one fails
445445
}
446446
}
@@ -459,7 +459,7 @@ export class PluginManager {
459459
const pluginLogger = this.logger?.child({ pluginId: plugin.meta.id }) || this.app!.log.child({ pluginId: plugin.meta.id });
460460
await plugin.shutdown(pluginLogger);
461461
} catch (error) {
462-
this.logger?.error(`Error shutting down plugin ${plugin.meta.id}:`, error);
462+
this.logger?.error({ error }, `Error shutting down plugin ${plugin.meta.id}:`);
463463
}
464464
}
465465
}

services/backend/src/routes/auth/changePassword.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ export default async function changePasswordRoute(fastify: FastifyInstance) {
219219
}
220220
} catch (emailError) {
221221
// Don't fail the password change if email fails
222-
fastify.log.warn('Failed to send password change notification email:', emailError);
222+
fastify.log.warn({ error: emailError }, 'Failed to send password change notification email:');
223223
}
224224

225225
// Optional: Invalidate all other sessions for security

services/backend/src/routes/auth/loginEmail.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ export default async function loginEmailRoute(server: FastifyInstance) {
303303

304304
// Send as raw JSON string to bypass any serialization issues
305305
const jsonString = JSON.stringify(cleanResponse);
306-
server.log.info('Sending login response:', jsonString);
306+
server.log.info({ response: jsonString }, 'Sending login response:');
307307
return reply.status(200).type('application/json').send(jsonString);
308308

309309
} catch (error) {

services/backend/src/routes/auth/registerEmail.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,7 @@ export default async function registerEmailRoute(server: FastifyInstance) {
380380
};
381381

382382
const jsonString = JSON.stringify(successResponse);
383-
server.log.info('Sending registration response:', jsonString);
383+
server.log.info({ response: jsonString }, 'Sending registration response:');
384384
return reply.status(201).type('application/json').send(jsonString);
385385

386386
} catch (error) {

services/backend/src/routes/db/setup.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ async function setupDbHandler(
142142
dbConfig = getDatabaseConfig(server.log);
143143
} catch (error) {
144144
const typedError = error as Error;
145-
server.log.error('Database configuration error:', typedError.message);
145+
server.log.error({ error: typedError.message }, 'Database configuration error:');
146146
return reply.status(400).send({
147147
error: 'Database configuration incomplete. Please check environment variables.',
148148
details: typedError.message
@@ -191,7 +191,7 @@ async function setupDbHandler(
191191

192192
// Send as raw JSON string to bypass any serialization issues
193193
const jsonString = JSON.stringify(cleanResponse);
194-
server.log.info('Sending clean response:', jsonString);
194+
server.log.info({ response: jsonString }, 'Sending clean response:');
195195
return reply.status(200).type('application/json').send(jsonString);
196196
} else {
197197
server.log.warn('Database initialization succeeded but re-initialization failed. Manual restart may be required.');
@@ -200,11 +200,11 @@ async function setupDbHandler(
200200
restart_required: true,
201201
database_type: String(dbType)
202202
};
203-
server.log.info('Sending response object:', JSON.stringify(responseObj));
203+
server.log.info({ response: JSON.stringify(responseObj) }, 'Sending response object:');
204204
return reply.status(200).send(responseObj);
205205
}
206206
} catch (reinitError) {
207-
server.log.error('Error during re-initialization after database setup:', reinitError);
207+
server.log.error({ error: reinitError }, 'Error during re-initialization after database setup:');
208208
return reply.status(200).send({
209209
message: 'Database setup successful, but re-initialization failed. Please restart the server to complete setup.',
210210
restart_required: true,

services/backend/src/routes/db/status.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ async function getDbStatusHandler(
4040

4141
// Send as raw JSON string to bypass any serialization issues
4242
const jsonString = JSON.stringify(cleanResponse);
43-
server.log.info('Sending status response:', jsonString);
43+
server.log.info({ response: jsonString }, 'Sending status response:');
4444
return reply.type('application/json').send(jsonString);
4545
} catch (error) {
4646
server.log.error(error, 'Error fetching database status'); // Use server.log

services/backend/src/routes/globalSettings/settings/bulk.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ export default async function bulkGlobalSettingsRoute(fastify: FastifyInstance)
100100
);
101101
results.push(setting);
102102
} catch (error) {
103-
fastify.log.error(`Error processing setting ${settingData.key}:`, error);
103+
fastify.log.error({ error }, `Error processing setting ${settingData.key}:`);
104104
errors.push({
105105
key: settingData.key,
106106
error: error instanceof Error ? error.message : 'Unknown error',

services/backend/src/routes/users/preferences/get.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ export default async function getPreferences(server: FastifyInstance) {
4949
const jsonString = JSON.stringify(successResponse);
5050
return reply.status(200).type('application/json').send(jsonString);
5151
} catch (error) {
52-
request.log.error('Error getting user preferences:', error);
52+
request.log.error({ error }, 'Error getting user preferences:');
5353

5454
const errorResponse: ErrorResponse = {
5555
success: false,

services/backend/src/routes/users/preferences/getSpecific.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ export default async function getSpecificPreference(server: FastifyInstance) {
7777
const jsonString = JSON.stringify(successResponse);
7878
return reply.status(200).type('application/json').send(jsonString);
7979
} catch (error) {
80-
request.log.error('Error getting specific preference:', error);
80+
request.log.error({ error }, 'Error getting specific preference:');
8181

8282
const errorResponse: ErrorResponse = {
8383
success: false,

services/backend/src/routes/users/preferences/notifications/acknowledge.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export default async function acknowledgeNotification(server: FastifyInstance) {
6969
const jsonString = JSON.stringify(successResponse);
7070
return reply.status(200).type('application/json').send(jsonString);
7171
} catch (error) {
72-
request.log.error('Error acknowledging notification:', error);
72+
request.log.error({ error }, 'Error acknowledging notification:');
7373

7474
const errorResponse: ErrorResponse = {
7575
success: false,

0 commit comments

Comments
 (0)