Welcome to our in-depth guide on using morgan for HTTP logging in Node.js! This tutorial is perfect for both beginners and intermediate developers looking to understand and implement this powerful logging tool.
šÆ Objective: Learn how to use the morgan library for logging HTTP requests in your Node.js applications.
morgan is a popular middleware for Node.js that provides HTTP request logging. It helps developers track and troubleshoot their applications by recording important details about incoming requests and responses.
š” Pro Tip: Installing morgan is as easy as running npm install morgan in your project directory.
To set up morgan, first, install it using npm (Node Package Manager). In your terminal, navigate to your project directory and run:
npm install morganNext, let's use morgan in our application by adding it to our app.js file:
const express = require('express');
const morgan = require('morgan');
const app = express();
// Add morgan middleware
app.use(morgan('dev'));Now, if you start your application, you'll see logging output similar to this:
> node app.js
...
(node:4655) WARNING: AccessControlPolicy does not declare allow self
[IP-ADDRESS] - - [DATE] "GET / HTTP/1.1" 200 - - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36"morgan allows you to customize the logging format to your needs. The format string, as passed to the middleware, controls what data is logged.
Here's an example with a custom format:
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));Now, the logging output will look like this:
GET /home 200 323 - 24 msš Note: You can find the full list of available tokens in the official documentation.
Let's create a simple HTTP server that logs incoming requests using morgan:
const express = require('express');
const morgan = require('morgan');
const app = express();
const PORT = 3000;
// Add morgan middleware
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
// Example route
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Now, if you start your application and navigate to http://localhost:3000, you'll see a log similar to this:
GET / 200 5 - 50 msmorgan also provides multiple stream support, which can help route logs to different destinations. This can be useful for separating out error logs from regular logs, or sending logs to a database or third-party logging service.
Here's an example using multiple streams:
const { createLogger, stream } = require('winston');
const morgan = require('morgan');
const express = require('express');
const app = express();
const PORT = 3000;
// Create a custom logger
const myFormat = morgan(':method :url :status :res[content-length] - :response-time ms', {
stream,
});
const logger = createLogger({
transports: [
new console.transport({ level: 'error' }),
new fileTransport({ filename: 'logs/error.log', level: 'error' }),
new fileTransport({ filename: 'logs/access.log' }),
],
});
app.use(myFormat);
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});In this example, we've used the winston library to create a custom logger and configured it to send error logs to the console and a file, while sending regular logs to a file.
Which command will install morgan as a dependency in your Node.js project?
That's it for our in-depth guide on using morgan for HTTP logging in Node.js! By understanding and implementing this powerful logging tool, you'll be able to track and troubleshoot your applications more effectively. Happy coding! š