Camkode
Camkode

Logging in Node.js: Best Tools and Practices

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.

Why Logging Matters

Logging is essential for:

  • Debugging: Identify the cause of bugs and crashes.
  • Monitoring: Keep an eye on system health and performance.
  • Auditing: Track user behavior and access logs.
  • Alerting: Get notified when something goes wrong.
  • Compliance: Meet regulatory or organizational requirements.

Here are some of the most widely used logging libraries and tools:

1. Console Logging (console.log)

  • Pros: Built-in, simple to use.
  • Cons: Lacks levels, formatting, and output redirection.
  • Use Case: Useful for quick debugging during development.

2. Winston

  • A powerful and flexible logging library with support for multiple transports (console, files, databases, etc.).
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"}

3. Pino

  • A super-fast JSON logger ideal for high-performance applications.
npm install pino

Example Usage:

const pino = require('pino');
const logger = pino();

logger.info('Server is running');
logger.error('An error occurred');

4. Bunyan

  • Another JSON logger, great for structured logging and log analysis tools.
npm install bunyan

Example Usage:

const bunyan = require('bunyan');
const logger = bunyan.createLogger({ name: 'myapp' });

logger.info('Starting up...');

Best Practices for Logging in Node.js

1. Use Log Levels

Standard log levels include:

  • error: Critical errors
  • warn: Warnings that don’t stop the app
  • info: General application events
  • debug: Detailed debug info

Use appropriate levels to filter logs later.

2. Use Structured Logging

Log data in structured formats like JSON. This makes it easier to parse and analyze with tools like ELK stack or Datadog.

3. Avoid Logging Sensitive Information

Never log passwords, tokens, or personal data. Sanitize logs to meet privacy and compliance standards.

4. Centralize Logs

In production, centralize logs using log aggregation services such as:

  • Loggly
  • Elasticsearch + Kibana
  • Datadog
  • Papertrail
  • AWS CloudWatch

5. Use Rotating Log Files

Avoid huge log files by using log rotation strategies. Winston and other libraries support this natively.

npm install winston-daily-rotate-file

6. Tag Logs with Context

Include context like request ID, user ID, endpoint path, etc. This helps trace issues across microservices or server instances.

Logging in Express Apps

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()),
  }
}));

Monitoring and Alerting

Pair logging with monitoring tools:

  • Prometheus + Grafana
  • New Relic
  • Sentry (for error logging)
  • Logz.io

Set up alerts for log entries with level error or specific keywords.

Secure Your Logs

  • Limit access to logs.
  • Encrypt logs in transit and at rest.
  • Set retention policies to delete old logs.

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.

Reference