Add Request Logger to Node.js APIs

Ismail Demirbilek
2 min readJul 16, 2024

--

When debugging edge cases in your Node.js APIs, logging each request can be incredibly helpful. By using a logger, you can capture important information about incoming requests and their details. In this guide, we’ll explore how to set up request logging in a Node.js applications along with Express.js middleware.

Pino is a small, high-performance logger for Node.js applications. Its minimal overhead makes it an excellent choice for logging in production environments.

Middlewares are very useful for executing code within a request / response cycle. Combining pino with an express midlleware provides all we need to log each request.

Here’s how to get started with Pino in an Express.js application. So let’s get started.

Setting Up a Basic Express.js Application

First, let’s create a simple Express.js application. Here’s a typical “Hello World” example:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
res.send('Hello World!');
});

app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});

Installing and Using Pino

To install Pino, run the following command:

$ npm i pino

Using Pino is straightforward. You instantiate a logger and call one of its methods, such as .info(), .debug(), or .error(). Here’s an example:

const logger = require('pino')({
level: process.env.LOG_LEVEL || 'debug'
});

logger.info('hello world');

You can customize the log level using environment variables, as shown above.

Adding a Request Logger Middleware

To log every request in your Express.js application, you can introduce a logger middleware. This middleware will log details about each request, such as the method, path, query parameters, and body.

Here’s how to set up the logger middleware:

// logger middleware
app.use((req, res, next) => {
logger.debug({
method: req.method,
path: req.path,
query: req.query,
body: req.body,
});
next();
});

Example Output

When a request is made, the logger will output information like this:

[1721131516300] DEBUG (server/73271 on SomeOnes-MacBook-Pro.local):
method: "POST"
path: "/"
query: {}
body: {}

Complete Code Example

Combining everything, here is the complete code for an Express.js application with Pino request logging:

const express = require('express');
const app = express();
const port = 3000;

const logger = require('pino')({
level: process.env.LOG_LEVEL || 'debug'
});

// logger middleware
app.use((req, res, next) => {
logger.debug({
method: req.method,
path: req.path,
query: req.query,
body: req.body,
});
next();
});

// APIs
app.get('/', (req, res) => {
res.send('Hello World!');
});

app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});

By following these steps, you can effectively log every request to your Node.js APIs, making it easier to debug and monitor your applications.

Happy debugging!

--

--