refactor: replace console.log with structured logger calls

Replace raw `console.log`/`console.error` calls across CLI, API
handlers, and module files with structured logger functions (`step`,
`done`, `warn`, `fail`) from the shared logger library.

This improves log consistency, readability, and makes it easier to
control output formatting and log levels from a single place.
This commit is contained in:
2026-04-12 21:44:00 -04:00
parent dd7c54d913
commit e87bd05fa4
25 changed files with 218 additions and 189 deletions
+8 -7
View File
@@ -7,6 +7,7 @@
*/
import { AVAILABLE_MODULES } from './modules.registry.js';
import { step, done, warn, fail, info } from '../shared/lib/logger.js';
/**
* Check if a module is enabled via environment variable
@@ -26,16 +27,16 @@ export async function initModules() {
const created = [];
const skipped = [];
console.log('\nInitializing module databases...');
step('Initializing module databases...');
for (const moduleName of AVAILABLE_MODULES) {
if (!isModuleEnabled(moduleName)) {
console.log(`- Skipped ${moduleName} (not enabled)`);
info(`Skipped ${moduleName} (not enabled)`);
continue;
}
try {
console.log(`\nInitializing ${moduleName} module tables...`);
step(`Initializing ${moduleName}...`);
const db = await import(`./${moduleName}/db.js`);
if (typeof db.createTables === 'function') {
@@ -44,15 +45,15 @@ export async function initModules() {
if (result?.created) created.push(...result.created);
if (result?.skipped) skipped.push(...result.skipped);
console.log(`${moduleName} module initialized`);
done(`${moduleName} initialized`);
} else {
console.log(`- ${moduleName} has no createTables function`);
info(`${moduleName} has no createTables function`);
}
} catch (error) {
if (error.code === 'ERR_MODULE_NOT_FOUND' || error.message?.includes('Cannot find module')) {
console.log(`- ${moduleName} has no db.js (skipped)`);
info(`${moduleName} has no db.js (skipped)`);
} else {
console.error(`Error initializing ${moduleName}:`, error.message);
fail(`${moduleName}: ${error.message}`);
}
}
}
+3 -2
View File
@@ -10,6 +10,7 @@
*/
import { getModule, getEnabledModules } from '@zen/core/core/modules';
import { fail } from '../shared/lib/logger.js';
// Static actions for internal modules (add entries here for new internal modules)
export const MODULE_ACTIONS = {
@@ -60,7 +61,7 @@ export async function getAllModuleDashboardStats() {
stats[moduleName] = result.stats;
}
} catch (error) {
console.error(`Error getting dashboard stats for ${moduleName}:`, error);
fail(`Error getting dashboard stats for ${moduleName}: ${error.message}`);
}
}
@@ -73,7 +74,7 @@ export async function getAllModuleDashboardStats() {
stats[mod.name] = result.stats;
}
} catch (error) {
console.error(`Error getting dashboard stats for ${mod.name}:`, error);
fail(`Error getting dashboard stats for ${mod.name}: ${error.message}`);
}
}
}
+2 -1
View File
@@ -15,6 +15,7 @@ import { PublicPagesLayout, PublicPagesClient } from '@zen/core/modules/pages';
import { getMetadataGenerator } from '@zen/core/modules/metadata';
import { getAppConfig } from '@zen/core';
import { getModuleActions } from '@zen/core/modules/actions';
import { fail } from '../shared/lib/logger.js';
/**
* Per-module path configuration.
@@ -62,7 +63,7 @@ export async function generateMetadata({ params }) {
try {
return await generator(token);
} catch (error) {
console.error(`[ZEN] Error generating metadata for ${moduleName}/${metadataType}:`, error);
fail(`Error generating metadata for ${moduleName}/${metadataType}: ${error.message}`);
}
}
}
+15 -14
View File
@@ -32,6 +32,7 @@ import {
} from '@zen/core/storage';
import { getPostsConfig, getPostType } from './config.js';
import { fail, warn } from '../../shared/lib/logger.js';
// ============================================================================
// Config
@@ -91,7 +92,7 @@ async function handleGetPosts(request) {
limit: result.pagination.limit
};
} catch (error) {
console.error('[Posts] Error GET posts:', error);
fail(`Posts: error GET posts: ${error.message}`);
return { success: false, error: error.message || 'Failed to fetch posts' };
}
}
@@ -111,7 +112,7 @@ async function handleCreatePost(request) {
const post = await createPost(postType, postData);
return { success: true, post, message: 'Post created successfully' };
} catch (error) {
console.error('[Posts] Error creating post:', error);
fail(`Posts: error creating post: ${error.message}`);
return { success: false, error: error.message || 'Failed to create post' };
}
}
@@ -148,7 +149,7 @@ async function handleUpdatePost(request) {
try {
await deleteFile(oldKey);
} catch (err) {
console.warn(`[Posts] Error deleting old image ${oldKey}:`, err.message);
warn(`Posts: error deleting old image ${oldKey}: ${err.message}`);
}
}
}
@@ -156,7 +157,7 @@ async function handleUpdatePost(request) {
return { success: true, post, message: 'Post updated successfully' };
} catch (error) {
console.error('[Posts] Error updating post:', error);
fail(`Posts: error updating post: ${error.message}`);
return { success: false, error: error.message || 'Failed to update post' };
}
}
@@ -174,7 +175,7 @@ async function handleDeletePost(request) {
if (!deleted) return { success: false, error: 'Post not found' };
return { success: true, message: 'Post deleted successfully' };
} catch (error) {
console.error('[Posts] Error deleting post:', error);
fail(`Posts: error deleting post: ${error.message}`);
return { success: false, error: 'Failed to delete post' };
}
}
@@ -221,7 +222,7 @@ async function handleUploadImage(request) {
return { success: true, key: uploadResult.data.key };
} catch (error) {
console.error('[Posts] Error uploading image:', error);
fail(`Posts: error uploading image: ${error.message}`);
return { success: false, error: error.message || 'Upload failed' };
}
}
@@ -268,7 +269,7 @@ async function handleGetCategories(request) {
limit: result.pagination.limit
};
} catch (error) {
console.error('[Posts] Error GET categories:', error);
fail(`Posts: error GET categories: ${error.message}`);
return { success: false, error: error.message || 'Failed to fetch categories' };
}
}
@@ -288,7 +289,7 @@ async function handleCreateCategory(request) {
const category = await createCategory(postType, categoryData);
return { success: true, category, message: 'Category created successfully' };
} catch (error) {
console.error('[Posts] Error creating category:', error);
fail(`Posts: error creating category: ${error.message}`);
return { success: false, error: error.message || 'Failed to create category' };
}
}
@@ -314,7 +315,7 @@ async function handleUpdateCategory(request) {
const category = await updateCategory(postType, parseInt(id), updates);
return { success: true, category, message: 'Category updated successfully' };
} catch (error) {
console.error('[Posts] Error updating category:', error);
fail(`Posts: error updating category: ${error.message}`);
return { success: false, error: error.message || 'Failed to update category' };
}
}
@@ -331,7 +332,7 @@ async function handleDeleteCategory(request) {
await deleteCategory(postType, parseInt(id));
return { success: true, message: 'Category deleted successfully' };
} catch (error) {
console.error('[Posts] Error deleting category:', error);
fail(`Posts: error deleting category: ${error.message}`);
if (error.message.includes('Cannot delete')) {
return { success: false, error: error.message };
}
@@ -356,7 +357,7 @@ async function handleSearchPosts(request) {
const posts = await searchPosts(postType, q, limit);
return { success: true, posts };
} catch (error) {
console.error('[Posts] Error searching posts:', error);
fail(`Posts: error searching posts: ${error.message}`);
return { success: false, error: error.message || 'Failed to search posts' };
}
}
@@ -406,7 +407,7 @@ async function handlePublicGetPosts(request, params) {
limit: result.pagination.limit
};
} catch (error) {
console.error('[Posts] Error public GET posts:', error);
fail(`Posts: error public GET posts: ${error.message}`);
return { success: false, error: error.message || 'Failed to fetch posts' };
}
}
@@ -421,7 +422,7 @@ async function handlePublicGetPostBySlug(request, params) {
if (!post) return { success: false, error: 'Post not found' };
return { success: true, post };
} catch (error) {
console.error('[Posts] Error public GET post by slug:', error);
fail(`Posts: error public GET post by slug: ${error.message}`);
return { success: false, error: error.message || 'Failed to fetch post' };
}
}
@@ -434,7 +435,7 @@ async function handlePublicGetCategories(request, params) {
const categories = await getActiveCategories(postType);
return { success: true, categories };
} catch (error) {
console.error('[Posts] Error public GET categories:', error);
fail(`Posts: error public GET categories: ${error.message}`);
return { success: false, error: error.message || 'Failed to fetch categories' };
}
}
+3 -2
View File
@@ -6,6 +6,7 @@
import { query } from '@zen/core/database';
import { deleteFile } from '@zen/core/storage';
import { warn } from '../../shared/lib/logger.js';
import { getPostType } from './config.js';
function slugify(text) {
@@ -438,10 +439,10 @@ export async function deletePost(postType, id) {
try {
const deleteResult = await deleteFile(imageKey);
if (!deleteResult.success) {
console.warn(`[Posts] Failed to delete image from storage: ${imageKey}`, deleteResult.error);
warn(`Posts: failed to delete image from storage: ${imageKey}${deleteResult.error}`);
}
} catch (err) {
console.warn(`[Posts] Error deleting image from storage: ${imageKey}`, err.message);
warn(`Posts: error deleting image from storage: ${imageKey}${err.message}`);
}
}
+10 -9
View File
@@ -5,6 +5,7 @@
import { query } from '@zen/core/database';
import { getPostsConfig } from './config.js';
import { done, info, step } from '../../shared/lib/logger.js';
async function tableExists(tableName) {
const result = await query(
@@ -23,7 +24,7 @@ async function createPostsCategoryTable() {
const exists = await tableExists(tableName);
if (exists) {
console.log(`- Table already exists: ${tableName}`);
info(`Table already exists: ${tableName}`);
return { created: false, tableName };
}
@@ -42,7 +43,7 @@ async function createPostsCategoryTable() {
await query(`CREATE INDEX idx_zen_posts_category_post_type ON zen_posts_category(post_type)`);
await query(`CREATE INDEX idx_zen_posts_category_is_active ON zen_posts_category(is_active)`);
console.log(`Created table: ${tableName}`);
done(`Created table: ${tableName}`);
return { created: true, tableName };
}
@@ -51,7 +52,7 @@ async function createPostsTable() {
const exists = await tableExists(tableName);
if (exists) {
console.log(`- Table already exists: ${tableName}`);
info(`Table already exists: ${tableName}`);
return { created: false, tableName };
}
@@ -73,7 +74,7 @@ async function createPostsTable() {
await query(`CREATE INDEX idx_zen_posts_category_id ON zen_posts(category_id)`);
await query(`CREATE INDEX idx_zen_posts_data_gin ON zen_posts USING GIN (data)`);
console.log(`Created table: ${tableName}`);
done(`Created table: ${tableName}`);
return { created: true, tableName };
}
@@ -82,7 +83,7 @@ async function createPostsRelationsTable() {
const exists = await tableExists(tableName);
if (exists) {
console.log(`- Table already exists: ${tableName}`);
info(`Table already exists: ${tableName}`);
return { created: false, tableName };
}
@@ -100,7 +101,7 @@ async function createPostsRelationsTable() {
await query(`CREATE INDEX idx_zen_posts_relations_post_id ON zen_posts_relations(post_id)`);
await query(`CREATE INDEX idx_zen_posts_relations_related ON zen_posts_relations(related_post_id)`);
console.log(`Created table: ${tableName}`);
done(`Created table: ${tableName}`);
return { created: true, tableName };
}
@@ -119,18 +120,18 @@ export async function createTables() {
// zen_posts_category must always be created before zen_posts
// because zen_posts has a FK reference to it
console.log('\n--- Posts Categories ---');
step('Posts Categories');
const catResult = await createPostsCategoryTable();
if (catResult.created) created.push(catResult.tableName);
else skipped.push(catResult.tableName);
console.log('\n--- Posts ---');
step('Posts');
const postResult = await createPostsTable();
if (postResult.created) created.push(postResult.tableName);
else skipped.push(postResult.tableName);
if (needsRelations) {
console.log('\n--- Posts Relations ---');
step('Posts Relations');
const relResult = await createPostsRelationsTable();
if (relResult.created) created.push(relResult.tableName);
else skipped.push(relResult.tableName);