Logging Requests in Your Node.js API

In this guide, we will explore how to log incoming requests in a Node.js API. Logging is essential for monitoring and debugging your application, and we'll provide practical examples to help you implement it effectively.
By Jamie

Introduction to Logging in Node.js APIs

Logging requests in your Node.js API can greatly enhance your ability to monitor application performance and diagnose issues. In this tutorial, we will discuss how to set up logging using a popular logging library called morgan, and we will demonstrate how to log requests to the console and a file.

Step 1: Setting Up Your Node.js Environment

Before we dive into logging, ensure you have Node.js and npm installed. If you haven’t already set up a basic Node.js API, you can create a simple one as follows:

Create Your Project

mkdir my-api
cd my-api
npm init -y
npm install express morgan

Create the Basic API Structure

Create a file named app.js:

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

const app = express();
const PORT = process.env.PORT || 3000;

// Use morgan for logging
app.use(morgan('combined'));

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

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Step 2: Understanding the Logging Format

In the above example, we used the combined format for morgan, which outputs detailed logs including:

  • Remote address
  • Request method
  • Request URL
  • HTTP version
  • Response status code
  • Response time in milliseconds

You can choose other predefined formats or create your own custom format based on your needs.

Step 3: Logging to a File

To log requests to a file instead of the console, you can use fs to create a write stream. Modify the app.js file as follows:

const fs = require('fs');
const path = require('path');

// Create a write stream (in append mode)
const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });

// Setup the logger to log to a file
app.use(morgan('combined', { stream: accessLogStream }));

Now, all incoming requests will be logged to access.log in the project directory.

Conclusion

Logging requests in your Node.js API is straightforward with morgan. By following the steps outlined above, you can easily implement logging to enhance your API’s observability and debugging capabilities. Remember to tailor the logging format and output according to your specific requirements. Happy coding!