Custom Logger Setup
Take control of logging by overwriting console.log to add timestamps, log levels, and formatted messages. Store logs in files, databases, or external services for better debugging and auditing in backend applications. Perfect for tracking errors and monitoring performance efficiently.
Why Use a Custom Logger?
Enhanced Debugging & Monitoring
Add timestamps, log levels, and structured messages to make debugging easier and logs more readable.
Persistent Log Storage
Store logs in files, databases, or external services to track errors, monitor performance, and audit activities.
No Extra Dependencies
Customize console logging without installing any additional packages—just pure JavaScript.
Overriding console.log
You can use this code to override console.log function and store logs in your database.
1import { dayjs } from './dayjs'; // or use any other date library23// * store the original console.log function since we will be overriding it4const originalConsoleLog = console.log;56const storeLogInDb = async (level, time, data) => {7// * store the log in your database or file system, write your own logic here8};910const logWithDb = async (level, originalMethod, ...args) => {11let message = '';12for (let i = 0; i < args.length; i++) {13const arg = args[i];14if (i >= 1) message += ' ';1516if (typeof arg === 'object') {17message += JSON.stringify(arg);18} else {19message += arg;20}21}22const time = dayjs().format('YYYY-MM-DD HH:mm:ss');2324// * store the log in your database or file system25storeLogInDb(level, time, `[${time}] ${message}`);2627// * call the original console.log function to print the message in your terminal also28originalMethod(...args);29};3031// * overriding console.log function32console.log = (...args) => logWithDb('log', originalConsoleLog, ...args);3334// ? you can do this with other console functions as well such as35// ? console.error, console.warn and console.info in order to classify logs36// ? import this file in your server.ts file and the console.log method will be overridden37// ? whenever you call console.log, it will be logged in your database or file system3839export { originalConsoleLog, logWithDb };
⭐️ Got a question or feedback?
Feel free to reach out!