bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Node.js/Perfomance & Scaling
Node.js•Perfomance & Scaling

Node.js Logging

Concept visual

Node.js Logging

push / pop from the top({[← top

Why Logging Matters

Effective logging is essential for several reasons:

Debugging:

Understand what's happening inside your application

Troubleshooting:

Diagnose issues in production environments

Monitoring:

Track application health and performance

Auditing:

Record important events for compliance and security

Analytics:

Gather data about application usage and behavior

Basic Logging with Console

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');

Console Limitations

While the console is convenient, it has significant limitations for production use:

No built-in log levels for filtering

No log rotation or file management

No structured output formats like JSON

Limited integration with monitoring systems

Note:

Console methods are synchronous when outputting to terminals/files and can impact performance if used frequently in production.

Structured Logging

Structured logging formats log messages as data objects (typically JSON) rather than plain text, making them easier to parse, search, and analyze.

Benefits of Structured Logging

Consistent format for machine readability

Better searchability and filtering

Simplified integration with log aggregation tools

Enhanced context with metadata

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

Next

Node.js Monitoring & Observability