DEV Community

Amit Tiwary
Amit Tiwary

Posted on • Edited on

4 2

Log API request and response in Nodejs

Logging helps us to debug our application and solve the issue easily. Before we added logging in backend we used to face problems in reproducing the bug related to API requests and responses. We used the logging tools to log the request and responses of the APIs. Loggly is a cloud-based log management tool. You can create a free account here. While creating an account it asks for the subdomain name that you need later. After creating an account, you have to set up the source.

loggly source setup
We are using Nodejs in the backend, so we selected the Nodejs as the source.

source selection
The custom token is required to initialize the Loggly. You will get it in the custom tokens tab.

token select

Once the account setup is completed, let's start integrating it into our code. We can install the Loggly using the npm install winston-loggly-bulk. We will need the subdomain and token to initialize the Loggly.

const winston = require('winston');
const { Loggly } = require('winston-loggly-bulk');
winston.add(new Loggly({
  token: 'custom token',
  subdomain: 'sub domain',
  tags: ['Winston-NodeJS'],
  json: true,
}));

Enter fullscreen mode Exit fullscreen mode

Now use the log to log the request and response of the api.

const winston = require('winston');
      winston.log('info', {
        url: `${req.protocol}://${req.get('host')}${req.originalUrl}`, body: req.body, method: req.method, response: res('response sent to the user'),
      });
Enter fullscreen mode Exit fullscreen mode

If everything is done correctly, you can see the logs from the log explorer

explorer

dashboard

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay