Node.js

How Do You Implement Request Logging in Node.js and Express.js?

When building a backend application, have you ever wondered how to find out which API a user called, how long a request took, or why a particular endpoint…

D
DevByteTechnical Author
Published
9 min read0 views
How Do You Implement Request Logging in Node.js and Express.js?

When building a backend application, have you ever wondered how to find out which API a user called, how long a request took, or why a particular endpoint returned an error?

For example, imagine you have a Node.js application with hundreds of API requests every minute. Suddenly, users report that the login API is slow. Without proper logging, identifying the problem can be difficult.

This is where request logging becomes useful.

Request logging helps developers track incoming HTTP requests, monitor API performance, investigate errors, and understand how an application behaves in production.

In this article, we will learn what request logging is, why it matters, and how to implement it in Node.js and Express.js using both custom middleware and the popular Morgan library.

What Is Request Logging?

Request logging is the process of recording information about HTTP requests and responses handled by a backend application.

Whenever a client sends a request to your server, you can record details such as:

  • HTTP method, such as GET, POST, PUT, or DELETE.

  • Request URL or API endpoint.

  • HTTP response status code.

  • Request processing time.

  • Request timestamp.

  • Client IP address, when available and appropriate.

  • Error details when a request fails.

For example, a request log might look like this:

2026-10-27T10:30:15.000Z GET /api/users 200 45ms
2026-10-27T10:30:18.000Z POST /api/login 401 12ms
2026-10-27T10:30:22.000Z GET /api/products 500 120ms

These logs tell us that the users API succeeded, the login request was unauthorized, and the products API encountered a server error.

The main purpose of request logging is to make an application's behavior easier to monitor, debug, and analyze.

Why Is Request Logging Important?

Request logging is useful throughout the development and production lifecycle.

1. Debugging API Errors

Suppose a user reports that an API is returning a 500 Internal Server Error.

Request logs can help you identify the affected endpoint, the time of the failure, and the request's status code. When combined with application error logs, they can help you find the underlying problem.

2. Monitoring API Performance

If an API usually responds in 50 milliseconds but suddenly takes 2 seconds, request-duration logs can help you identify the slowdown.

You can investigate whether the cause is a slow database query, an external API, or expensive application logic.

3. Understanding Application Traffic

Logs help you understand which endpoints receive the most requests and how frequently clients encounter errors.

This information can help you plan caching, database optimization, and infrastructure improvements.

4. Investigating Security Issues

Request logs can help identify unusual patterns, such as repeated failed login attempts or requests to unexpected endpoints.

However, logs should not be treated as a complete security solution. They should be combined with appropriate authentication, authorization, rate limiting, and monitoring.

Method 1: Implement Request Logging Using Custom Middleware

Express.js middleware is one of the simplest ways to implement request logging.

Middleware functions can access the incoming request and outgoing response, making them suitable for recording request information.

Let's build a basic implementation.

Step 1: Create an Express.js Application

First, create a project and install Express.js.

mkdir request-logging-demo
cd request-logging-demo

npm init -y
npm install express

Create an index.js file:

const express = require("express");

const app = express();

app.use(express.json());

app.get("/", (req, res) => {
  res.json({
    message: "Welcome to the API",
  });
});

app.get("/api/users", (req, res) => {
  res.json({
    users: [
      { id: 1, name: "Manjeet" },
      { id: 2, name: "Rahul" },
    ],
  });
});

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

Start the application:

node index.js

Our Express server is now running on port 3000.

However, it does not yet record incoming requests. Let's add middleware to solve that problem.

Step 2: Create Request Logging Middleware

Add the following middleware before your route definitions:

const requestLogger = (req, res, next) => {
  const startTime = Date.now();

  res.on("finish", () => {
    const duration = Date.now() - startTime;

    console.log({
      method: req.method,
      url: req.originalUrl,
      statusCode: res.statusCode,
      duration: `${duration}ms`,
      timestamp: new Date().toISOString(),
    });
  });

  next();
};

app.use(requestLogger);

Now, your application will record request information after the response has finished.

For example, requesting /api/users might produce this output:

{
  method: "GET",
  url: "/api/users",
  statusCode: 200,
  duration: "8ms",
  timestamp: "2026-10-27T10:30:15.000Z"
}

Let's understand how this middleware works.

const startTime = Date.now()

This records the time when the request enters the middleware.

res.on("finish", ...)

The finish event fires when the response has been handed off for transmission by Node.js. It allows us to record the final response status and calculate the time taken to process the request.

Date.now() - startTime

This calculates the elapsed time in milliseconds.

next()

This passes control to the next middleware function or route handler.

Why Should Logging Middleware Be Registered Early?

Middleware execution follows the order in which middleware and routes are registered.

Therefore, register your request logger before your route definitions so it can observe requests handled by those routes.

If you register the logger after your routes, it might never run for requests that have already received a response.

Method 2: Implement Request Logging Using Morgan

Writing custom middleware is useful when you need complete control over log formatting. However, many applications use an existing logging middleware library.

One popular option is Morgan, an HTTP request logger for Node.js and Express.js.

Morgan provides predefined logging formats, so you do not need to implement basic request logging yourself.

Step 1: Install Morgan

Run the following command:

npm install morgan

Step 2: Configure Morgan in Express.js

Import Morgan and register it as middleware:

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

const app = express();

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

app.get("/", (req, res) => {
  res.send("Welcome to the API");
});

app.get("/api/users", (req, res) => {
  res.json({
    message: "Users fetched successfully",
  });
});

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

When you send a request to /api/users, Morgan prints a log similar to this:

GET /api/users 200 4.123 ms - 37

The output contains the HTTP method, URL, response status, request-processing time, and response size.

Common Morgan Logging Formats

Morgan provides several built-in formats.

Format

Description

dev

Concise, colorized logs intended primarily for development.

combined

Detailed logs commonly used in production environments.

common

A standard, more compact access-log format.

short

A shorter format containing useful request information.

tiny

A minimal format with basic request details.

For example, during development, you can use:

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

For more detailed access logs, you can use:

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

The appropriate format depends on your application's logging and monitoring requirements.

Method 3: Save Request Logs to a File

Printing logs in the terminal is convenient during development. However, terminal output alone is usually insufficient for production applications.

You may need to retain logs so that you can investigate issues after they occur.

Morgan supports writing logs to a writable stream. Node.js provides the fs module, which can create a file stream for this purpose.

Consider the following example:

const express = require("express");
const morgan = require("morgan");
const fs = require("node:fs");
const path = require("node:path");

const app = express();

const logDirectory = path.join(__dirname, "logs");

fs.mkdirSync(logDirectory, {
  recursive: true,
});

const accessLogStream = fs.createWriteStream(
  path.join(logDirectory, "access.log"),
  { flags: "a" }
);

app.use(morgan("combined", {
  stream: accessLogStream,
}));

app.get("/", (req, res) => {
  res.send("Welcome to the API");
});

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

After making requests, you will find the access logs in:

logs/access.log

The flags: "a" option opens the file in append mode, allowing new log entries to be added without replacing existing contents.

The recursive: true option ensures that the log directory is created if it does not already exist.

Important: This example demonstrates basic file-based logging. For production deployments, configure log rotation, retention limits, disk-space monitoring, and appropriate access permissions. In containerized or cloud environments, writing structured logs to standard output and collecting them through a centralized logging platform may be a better approach.

Method 4: Create Structured Request Logs

As applications become larger, plain-text logs can become difficult to search and analyze.

Structured logging stores log information in a consistent format, such as JSON.

For example:

{
  "level": "info",
  "method": "GET",
  "url": "/api/users",
  "statusCode": 200,
  "durationMs": 15,
  "timestamp": "2026-10-27T10:30:15.000Z"
}

Structured logs are easier for monitoring platforms to filter and analyze.

For example, you could search for all requests where the status code is greater than or equal to 500 or identify endpoints whose response times exceed a particular threshold.

You can generate JSON logs with a custom middleware:

const requestLogger = (req, res, next) => {
  const startTime = Date.now();

  res.on("finish", () => {
    const log = {
      method: req.method,
      url: req.originalUrl,
      statusCode: res.statusCode,
      durationMs: Date.now() - startTime,
      timestamp: new Date().toISOString(),
    };

    console.log(JSON.stringify(log));
  });

  next();
};

app.use(requestLogger);

This approach is a useful starting point. For larger applications, a dedicated logging library such as Pino or Winston can provide additional features, including log levels, structured fields, and configurable transports.

Best Practices for Request Logging

Implementing request logging is straightforward, but designing a useful and secure logging system requires some care.

1. Do Not Log Sensitive Information

Never log passwords, authentication tokens, session cookies, or other secrets.

Avoid logging entire request bodies by default because they may contain personal information, payment details, or credentials.

Instead, log only the information necessary for debugging and monitoring.

2. Measure Request Duration

Response time is an important indicator of API performance.

Recording the duration of each request helps you identify slow endpoints and investigate performance regressions.

For more precise measurements in Node.js, you can also use performance.now() from the node:perf_hooks module.

3. Include the HTTP Status Code

The status code helps distinguish successful requests from client errors and server errors.

For example:

  • 200: Request succeeded.

  • 400: Bad request.

  • 401: Authentication required or failed.

  • 403: Access forbidden.

  • 404: Resource not found.

  • 500: Internal server error.

Monitoring these codes can help you identify API problems more quickly.

4. Use Request IDs

When an application handles many concurrent requests, a request ID can help you trace a single request across multiple services.

For example:

{
  "requestId": "req-12345",
  "method": "POST",
  "url": "/api/orders",
  "statusCode": 201,
  "durationMs": 32
}

Generate or accept request IDs carefully. If you accept an ID from an incoming header, validate it and avoid trusting arbitrary values without limits. For distributed systems, propagate the same correlation identifier through relevant services.

5. Use Different Log Levels

Not every event has the same importance.

Common log levels include:

  • debug: Detailed information useful during development.

  • info: Normal application activity.

  • warn: Unexpected conditions that do not necessarily cause failure.

  • error: Failures that require investigation.

A logging library makes it easier to control which messages are emitted in each environment.

6. Avoid Excessive Logging

Logging every detail of every request can increase storage costs and make important events harder to find.

Choose meaningful fields, apply appropriate retention policies, and consider sampling high-volume traffic when necessary.

7. Configure Logging for Production

For a production application, consider structured logging, centralized log collection, log rotation or retention, restricted access, and alerts for important error patterns.

Also remember that res.on("finish") records when the response has finished being handed off for transmission; it does not prove that the client received or processed the response successfully.

Conclusion

Request logging is an important part of building reliable Node.js and Express.js applications. It helps developers understand API traffic, investigate errors, and monitor application performance.

For a small application, custom Express middleware may be enough. If you want a quick, established solution, Morgan provides convenient request-logging formats. For larger production systems, structured logging and a dedicated logging library can make logs easier to manage and analyze.

Start with the essentials: HTTP method, URL, status code, timestamp, and request duration. Add request IDs and centralized log collection as your application grows.

By implementing request logging early, you make your backend easier to debug, monitor, and maintain.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘