Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Logging in Node.js
Logging is a very essential part in any application whether it is made in Node.js or any other programming languages. Logging helps us to detect weird behaviours of an application along with real-time errors and exceptions. One should definitely put logical logs in their application. These logs help the user to identify any mistakes and resolve it on urgent basis.
There are 5 different log levels which are present at the moment with the user. These log levels are used to define different kinds of logs and helps the user to identify different scenarios. The log levels must be carefully configured to get the best deal out of these logs:
error - Critical issues that need immediate attention
warn - Warning messages for potential issues
info - General information about application flow
verbose - Detailed information for debugging
debug - Detailed debug information for development
Console Logging (Built-in)
Node.js provides built-in console methods for basic logging. While simple, it's suitable for development and small applications:
console.log("Info: Server started");
console.error("Error: Database connection failed");
console.warn("Warning: Deprecated API used");
// With timestamps
console.log(new Date().toISOString(), "User logged in");
Info: Server started Error: Database connection failed Warning: Deprecated API used 2024-01-15T10:30:45.123Z User logged in
Winston Package
Winston is the most popular logging library for Node.js, providing different log levels, transports, and formatting options:
const winston = require('winston');
// Create logger with console and file transports
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ timestamp, level, message }) => {
return `${timestamp} [${level.toUpperCase()}]: ${message}`;
})
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'app.log' })
]
});
// Using different log levels
logger.error('Database connection failed');
logger.warn('API rate limit approaching');
logger.info('User authentication successful');
logger.debug('Request processing details');
2024-01-15T10:30:45.123Z [ERROR]: Database connection failed 2024-01-15T10:30:45.124Z [WARN]: API rate limit approaching 2024-01-15T10:30:45.125Z [INFO]: User authentication successful
Express Logging Middleware
You can create middleware to automatically log HTTP requests and responses in Express applications:
const express = require('express');
const winston = require('winston');
const app = express();
// Configure Winston logger
const logger = winston.createLogger({
level: 'info',
transports: [new winston.transports.Console()]
});
// Request logging middleware
function logRequest(req, res, next) {
logger.info(`${req.method} ${req.url} - ${req.ip}`);
next();
}
// Error logging middleware
function logError(err, req, res, next) {
logger.error(`Error: ${err.message} - Route: ${req.url}`);
next(err);
}
// Apply middleware
app.use(logRequest);
app.use(logError);
Debug Module
The debug module provides conditional logging based on environment variables, perfect for development debugging:
const debug = require('debug')('app:server');
// These logs only appear when DEBUG=app:server is set
debug('Server starting...');
debug('Database connected');
debug('Routes initialized');
console.log('To see debug logs, run: DEBUG=app:server node app.js');
To see debug logs, run: DEBUG=app:server node app.js
Comparison of Logging Approaches
| Method | Use Case | Features | Best For |
|---|---|---|---|
| Console | Development | Simple, built-in | Quick debugging |
| Winston | Production | Multiple transports, formatting | Enterprise applications |
| Debug | Development | Conditional logging | Library development |
Best Practices
Use appropriate log levels - don't log everything as 'info'
Include timestamps and context information
Log to files in production, console in development
Avoid logging sensitive information like passwords
Implement log rotation to prevent disk space issues
Conclusion
Choose console logging for simple applications, Winston for production systems requiring robust logging features, and debug module for conditional development logging. Proper logging strategy improves application maintainability and debugging efficiency.
