Posted by Kosal
Effective logging is one of the most important aspects of building and maintaining Node.js applications. It helps developers debug issues, monitor performance, and understand application behavior in real time. In this article, we’ll cover the best tools and practices for logging in Node.js so you can build more reliable and maintainable applications.
Logging is essential for:
Here are some of the most widely used logging libraries and tools:
console.log
)npm install winston
Example Usage:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'logs/app.log' }),
],
});
logger.info('Application started');
logger.error('Something went wrong');
The logs/app.log file should contain entries that look like this:
{"level":"info","message":"Application started","timestamp":"2025-05-20T03:42:31.453Z"}
{"level":"error","message":"Something went wrong","timestamp":"2025-05-20T03:42:31.456Z"}
npm install pino
Example Usage:
const pino = require('pino');
const logger = pino();
logger.info('Server is running');
logger.error('An error occurred');
npm install bunyan
Example Usage:
const bunyan = require('bunyan');
const logger = bunyan.createLogger({ name: 'myapp' });
logger.info('Starting up...');
Standard log levels include:
error
: Critical errorswarn
: Warnings that don’t stop the appinfo
: General application eventsdebug
: Detailed debug infoUse appropriate levels to filter logs later.
Log data in structured formats like JSON. This makes it easier to parse and analyze with tools like ELK stack or Datadog.
Never log passwords, tokens, or personal data. Sanitize logs to meet privacy and compliance standards.
In production, centralize logs using log aggregation services such as:
Avoid huge log files by using log rotation strategies. Winston and other libraries support this natively.
npm install winston-daily-rotate-file
Include context like request ID, user ID, endpoint path, etc. This helps trace issues across microservices or server instances.
Here’s how to add request-level logging using middleware:
const morgan = require('morgan');
app.use(morgan('combined'));
Or integrate morgan
with winston
:
app.use(morgan('combined', {
stream: {
write: message => logger.info(message.trim()),
}
}));
Pair logging with monitoring tools:
Set up alerts for log entries with level error
or specific keywords.
Logging is more than console.log
. In production environments, you need structured, scalable, and secure logging to build reliable applications. Tools like Winston, Pino, and Bunyan, along with best practices like using log levels and centralized logging, will help you gain full visibility into your Node.js apps.