Stackbits
Utilities > Custom Logger

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?

1

Enhanced Debugging & Monitoring

Add timestamps, log levels, and structured messages to make debugging easier and logs more readable.

2

Persistent Log Storage

Store logs in files, databases, or external services to track errors, monitor performance, and audit activities.

3

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.

1
import { dayjs } from './dayjs'; // or use any other date library
2
3
// * store the original console.log function since we will be overriding it
4
const originalConsoleLog = console.log;
5
6
const storeLogInDb = async (level, time, data) => {
7
// * store the log in your database or file system, write your own logic here
8
};
9
10
const logWithDb = async (level, originalMethod, ...args) => {
11
let message = '';
12
for (let i = 0; i < args.length; i++) {
13
const arg = args[i];
14
if (i >= 1) message += ' ';
15
16
if (typeof arg === 'object') {
17
message += JSON.stringify(arg);
18
} else {
19
message += arg;
20
}
21
}
22
const time = dayjs().format('YYYY-MM-DD HH:mm:ss');
23
24
// * store the log in your database or file system
25
storeLogInDb(level, time, `[${time}] ${message}`);
26
27
// * call the original console.log function to print the message in your terminal also
28
originalMethod(...args);
29
};
30
31
// * overriding console.log function
32
console.log = (...args) => logWithDb('log', originalConsoleLog, ...args);
33
34
// ? you can do this with other console functions as well such as
35
// ? console.error, console.warn and console.info in order to classify logs
36
// ? import this file in your server.ts file and the console.log method will be overridden
37
// ? whenever you call console.log, it will be logged in your database or file system
38
39
export { originalConsoleLog, logWithDb };

⭐️ Got a question or feedback?
Feel free to reach out!