nodejs logo

Logging and Monitoring in Node.js

Overview

Logging and monitoring are crucial for understanding application performance, diagnosing issues, and ensuring reliability. This guide covers best practices for implementing logging and monitoring in Node.js applications.

Why Logging and Monitoring?

Effective logging helps track the application's behavior and troubleshoot problems, while monitoring tools provide insights into performance and usage metrics.

Using Winston for Logging

The winston library is a versatile logging library for Node.js:

npm install winston

Example of setting up a basic logger with Winston:

const winston = require('winston');

// Create a logger instance
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'combined.log' }),
  ],
});

// Logging messages
logger.info('Information message');
logger.error('Error message');

Structured Logging

Using structured logging helps improve searchability and analysis of log entries. Here’s an example of logging with additional context:

logger.info('User login attempt', {
  username: 'user123',
  timestamp: new Date().toISOString(),
});

Monitoring with Prometheus and Grafana

For monitoring your Node.js applications, you can use Prometheus for metrics collection and Grafana for visualization:

npm install prom-client

Example of integrating Prometheus metrics in a Node.js app:

const client = require('prom-client');
const express = require('express');

const app = express();
const collectDefaultMetrics = client.collectDefaultMetrics;
collectDefaultMetrics({ timeout: 5000 });

// Create a custom metric
const requestsCounter = new client.Counter({
  name: 'http_requests_total',
  help: 'Total number of HTTP requests',
});

// Increment the counter for each request
app.use((req, res, next) => {
  requestsCounter.inc();
  next();
});

// Endpoint to expose metrics
app.get('/metrics', (req, res) => {
  res.set('Content-Type', client.register.contentType);
  res.end(client.register.metrics());
});

Best Practices

Follow these best practices for effective logging and monitoring:

  • Log at various levels (info, warn, error) to categorize log messages.
  • Use structured logging for better analysis and correlation.
  • Implement monitoring to track performance metrics and alert on issues.
  • Regularly review logs and metrics for insights and optimizations.
© 2024 Logging and Monitoring Guide