Paramclasses Academy - Blog

Tutorials Details

←
Post 36 of 40
→

Logging and Monitoring in Node.js: Practical Tools and Patterns

Logging and Monitoring in Node.js: Practical Tools and Patterns

October 30, 2026

✦ Logging and Monitoring in Node.js: Practical Tools and Patterns

When building a Node.js application, developers need to do more than write code and run a server. They also need to understand what is happening inside the application, identify errors, monitor performance, and troubleshoot unexpected problems.

This is where Logging and Monitoring become important.

Logging helps developers record application events, warnings, and errors. Monitoring helps track application health, performance, resource usage, and availability.

In this tutorial, you will learn how to implement logging in Node.js using Console, Morgan, and Winston. You will also understand error logging, log files, monitoring metrics, and production best practices.

✦ 1. What Is Logging in Node.js?

Logging is the process of recording information about an application's activities.

For example, when a user logs in, an API receives a request, or a database connection fails, the application can record these events.

A simple Node.js logging example:

console.log("Server started successfully");

console.warn("Database response is slow");

console.error("Unable to connect to database");

These messages help developers understand application behavior.

❖ Common Types of Logs

Log Level Purpose
info General application information
warn Potential problems
error Application errors
debug Detailed debugging information
fatal Critical failures requiring immediate attention

Different logging libraries may support different log levels and configurations.

✦ 2. Why Is Logging Important?

Logging is useful for both development and production applications.

Important benefits include:

  • Identifying application errors.

  • Tracking API requests.

  • Troubleshooting database problems.

  • Understanding user activity.

  • Investigating unexpected behavior.

  • Tracking background jobs.

  • Supporting application maintenance.

For example, if a login API suddenly stops working, useful logs can help developers identify whether the issue is related to authentication, database connectivity, or another part of the application.

✦ 3. Basic Logging Using Console

Node.js provides built-in console methods.

Create a file named app.js:

console.log("Application started");

console.info("User registration successful");

console.warn("Server memory usage is increasing");

console.error("Database connection failed");

console.debug("Debug information");

Run the application:

node app.js

The messages will appear in your terminal.

Console logging is useful for small applications and quick debugging. However, larger applications often need structured logs, different log levels, and persistent log storage.

✦ 4. Create a Node.js Logging Project

Create a new project:

mkdir node-logging-project
cd node-logging-project

Initialize Node.js:

npm init -y

Install Express:

npm install express

Your project structure will look like this:

node-logging-project/
│
├── node_modules/
├── package.json
├── server.js
└── logs/

We will add logging libraries in the following sections.

✦ 5. HTTP Request Logging Using Morgan

Morgan is middleware used to log HTTP requests in Express.js applications.

It can record details such as:

  • HTTP method.

  • Request URL.

  • Response status code.

  • Response time.

  • Response content length.

Install Morgan:

npm install morgan

Create server.js:

const express = require("express");
const morgan = require("morgan");

const app = express();

app.use(morgan("dev"));

app.get("/", (req, res) => {
    res.send("Node.js Application Running");
});

app.get("/users", (req, res) => {
    res.json({
        users: ["Rahul", "Amit", "Priya"]
    });
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

Start the server:

node server.js

Open:

http://localhost:3000

Morgan will display request information in the terminal whenever a browser or API client sends a request.

❖ Morgan Common Formats

Format Description
dev Short development-friendly logs
combined Detailed Apache-style request logs
common Common Apache-style request logs
short Short request information
tiny Minimal request information

Morgan is particularly useful for monitoring incoming HTTP requests during development and troubleshooting.

✦ 6. Logging with Winston in Node.js

Winston is a popular logging library for Node.js. It supports multiple log levels, custom formatting, and different log destinations called transports.

Install Winston:

npm install winston

Create a file named logger.js:

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/error.log",
            level: "error"
        }),

        new winston.transports.File({
            filename: "logs/combined.log"
        })
    ]
});

module.exports = logger;

This configuration creates three logging destinations:

  1. Console: Displays logs in the terminal.

  2. error.log: Stores error-level logs.

  3. combined.log: Stores logs at the configured minimum level and above.

Important: Create the logs directory before starting this application. Winston's file transport does not automatically create every missing parent directory.

✦ 7. Use Winston in an Express Application

Now use your logger inside server.js.

const express = require("express");
const morgan = require("morgan");
const logger = require("./logger");

const app = express();

app.use(express.json());

app.use(morgan("dev"));

app.get("/", (req, res) => {

    logger.info("Home API accessed");

    res.json({
        message: "Welcome to Node.js Logging"
    });

});

app.get("/users", (req, res) => {

    logger.info("Users API accessed");

    res.json({
        users: ["Rahul", "Amit", "Priya"]
    });

});

app.get("/error", (req, res) => {

    logger.error("Testing application error logging");

    res.status(500).json({
        message: "Something went wrong"
    });

});

app.listen(3000, () => {

    logger.info("Server started on port 3000");

});

Run:

node server.js

When you access the API endpoints, Winston records application messages in the configured destinations.

Morgan and Winston have different responsibilities:

  • Morgan records HTTP request information.

  • Winston records application-specific events and errors.

✦ 8. Create a Custom Error Logging Middleware

In Express.js, centralized error-handling middleware helps manage unexpected application errors.

Add the following middleware after your routes and before starting the server:

app.use((err, req, res, next) => {

    logger.error("Application Error", {
        message: err.message,
        method: req.method,
        url: req.originalUrl
    });

    res.status(500).json({
        success: false,
        message: "Internal Server Error"
    });

});

You can test it using an API route:

app.get("/test-error", (req, res, next) => {

    next(new Error("Database operation failed"));

});

Visit:

http://localhost:3000/test-error

The error middleware will record the error and return a generic response to the client.

In production, avoid sending stack traces or internal error details to users. You can include stack traces in restricted development logs when appropriate.

✦ 9. Log Different Levels Using Winston

Winston supports different logging levels.

Example:

logger.error("Payment processing failed");

logger.warn("API response is slow");

logger.info("User logged in successfully");

logger.debug("Debugging database query");

You can also configure the logging level through an environment variable.

For example:

const logger = winston.createLogger({
    level: process.env.LOG_LEVEL || "info",

    format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.json()
    ),

    transports: [
        new winston.transports.Console()
    ]
});

Set the environment variable:

LOG_LEVEL=debug

With Winston's standard levels, a logger configured at info records info and more severe levels, but not debug.

✦ 10. What Is Monitoring in Node.js?

Monitoring means continuously checking the health and performance of an application.

Logging tells developers what happened. Monitoring helps them understand the current condition and trends of the application.

Important monitoring metrics include:

Metric Purpose
CPU Usage Measures processor consumption
Memory Usage Tracks application memory
Response Time Measures API response duration
Error Rate Tracks failed requests
Request Count Measures incoming traffic
Uptime Tracks application availability

For example, if API response time suddenly increases, monitoring tools can help identify a performance issue.

✦ 11. Monitor Node.js Memory Usage

Node.js provides the built-in process.memoryUsage() method.

Example:

const memory = process.memoryUsage();

console.log("RSS:", memory.rss);

console.log("Heap Total:", memory.heapTotal);

console.log("Heap Used:", memory.heapUsed);

console.log("External:", memory.external);

These values are returned in bytes.

You can convert them into megabytes:

const memory = process.memoryUsage();

const heapUsedMB = (
    memory.heapUsed / 1024 / 1024
).toFixed(2);

console.log("Heap Used:", heapUsedMB, "MB");

This is useful for basic memory inspection and debugging.

✦ 12. Monitor Application Health with a Health Check API

A health check endpoint allows monitoring systems or deployment platforms to check whether an application is responding.

Example:

app.get("/health", (req, res) => {

    res.status(200).json({
        status: "OK",
        uptime: process.uptime(),
        timestamp: new Date().toISOString()
    });

});

Open:

http://localhost:3000/health

Example response:

{
    "status": "OK",
    "uptime": 125.45,
    "timestamp": "2026-10-30T10:00:00.000Z"
}

The timestamp and uptime will depend on your running application.

For production systems, a health endpoint can also check critical dependencies such as database connectivity. Keep liveness and readiness checks separate when your deployment environment requires them.

✦ 13. Popular Monitoring Tools for Node.js

Several tools can help developers monitor applications in production.

❖ 1. PM2

PM2 is a process manager for Node.js applications.

It can help:

  • Keep applications running.

  • Restart applications after crashes.

  • Manage application processes.

  • Display CPU and memory usage.

  • Collect application logs.

Install:

npm install -g pm2

Start your application:

pm2 start server.js

View running processes:

pm2 list

View logs:

pm2 logs

❖ 2. Prometheus

Prometheus is a monitoring and metrics collection system. It can collect application metrics and evaluate configured alerting rules.

It is useful for applications that need detailed metrics and infrastructure monitoring.

❖ 3. Grafana

Grafana helps developers visualize monitoring data through dashboards and charts.

It is commonly used with Prometheus and other data sources.

❖ 4. Sentry

Sentry helps developers capture and investigate application errors.

It can provide information about exceptions, stack traces, and application issues.

Choose monitoring tools according to your application's size, infrastructure, and operational requirements.

✦ 14. Important Logging Security Best Practices

Logs are useful, but they can also contain sensitive information if they are not designed carefully.

Follow these practices:

  1. Never log user passwords.

  2. Never log access tokens or private API keys.

  3. Avoid storing complete payment card information.

  4. Mask sensitive personal information when necessary.

  5. Use structured logs for easier searching.

  6. Restrict access to log files and monitoring dashboards.

  7. Configure log rotation and retention policies.

  8. Monitor unusual error patterns.

  9. Avoid logging unnecessary request bodies.

  10. Use centralized log storage when managing multiple servers.

For production applications, logs should be useful for debugging without exposing private user information.

✦ 15. Practical Project Structure

After implementing the examples, your project can have the following structure:

node-logging-project/
│
├── node_modules/
│
├── logs/
│   ├── error.log
│   └── combined.log
│
├── logger.js
├── server.js
├── package.json
└── .gitignore

Add the following to .gitignore:

node_modules/
.env
logs/

Whether logs should be excluded from version control depends on your deployment and log-storage strategy. Production logs should be stored in an appropriate secured location.

✦ Frequently Asked Questions (FAQs)

❖ Q1. What is logging in Node.js?

Logging is the process of recording application events, warnings, errors, and other useful information to help developers understand and troubleshoot an application.

❖ Q2. What is Winston in Node.js?

Winston is a logging library that supports multiple log levels, custom formats, and destinations such as console output and log files.

❖ Q3. What is Morgan in Express.js?

Morgan is HTTP request logging middleware that records information about incoming requests and their responses.

❖ Q4. What is the difference between logging and monitoring?

Logging records application events, while monitoring tracks application health, performance, availability, and resource usage.

❖ Q5. What is PM2 used for?

PM2 is a Node.js process manager that helps manage application processes, restarts, logs, and resource monitoring.

❖ Q6. Why is application monitoring important?

Monitoring helps developers identify performance issues, application failures, unusual traffic, and resource problems before they significantly affect users.

✦ Conclusion

Logging and monitoring are important parts of professional Node.js development. Morgan helps track HTTP requests, Winston provides structured application logging, and tools such as PM2, Prometheus, Grafana, and Sentry help monitor applications and investigate problems.

By implementing proper logging, health checks, error handling, and monitoring practices, developers can build Node.js applications that are easier to maintain and troubleshoot.

At Param Classes, students can learn Node.js, Express.js, backend development, database connectivity, and practical application development through hands-on training.

Visit Param Classes: https://paramclasses.in/

←
Post 36 of 40
→