Loading lesson path
Concept visual
Effective logging is essential for several reasons:
Formula
Node.js provides built - in console methods for basic logging:// Basic logging console.log('Info message');
console.error('Error message');
console.warn('Warning message');
console.debug('Debug message');
// Log objects const user = { id: 1, name: 'John', roles: ['admin', 'user'] };
console.log('User object:', user);
// Table output for arrays or objects console.table([
{ name: 'John', age: 30, role: 'admin' },
{ name: 'Jane', age: 25, role: 'user' },
{ name: 'Bob', age: 40, role: 'guest' }
]);
// Timing operations console.time('operation');// Perform some operations...
for (let i = 0; i < 1000000; i++) {// Do something
}
console.timeEnd('operation'); // Outputs: operation: 4.269ms
// Grouping related logs console.group('User Processing');
console.log('Loading user data...');
console.log('Validating user...');
console.log('Updating user profile...');
console.groupEnd();
// Stack trace console.trace('Trace message');While the console is convenient, it has significant limitations for production use:
Console methods are synchronous when outputting to terminals/files and can impact performance if used frequently in production.
Structured logging formats log messages as data objects (typically JSON) rather than plain text, making them easier to parse, search, and analyze.
Example of a Structured Log Entry (JSON)
{Formula
"timestamp": "2023 - 11 - 28T15:24:39.123Z","level": "error", "message": "Failed to connect to database",
Formula
"service": "user - service","context": {Formula
"requestId": "req - 123 - 456",
"userId": "user - 789","databaseHost": "db.example.com"
},
"error": {
"name": "ConnectionError",
"message": "Connection refused",
"stack": "..."
}
}Popular Node.js Logging Libraries