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.
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:
mkdir my-api
cd my-api
npm init -y
npm install express morgan
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}`);
});
In the above example, we used the combined
format for morgan
, which outputs detailed logs including:
You can choose other predefined formats or create your own custom format based on your needs.
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.
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!