DEV Community

Cover image for How to Use Morgan in Your Node.js Project
Thomas Sentre
Thomas Sentre

Posted on • Edited on

How to Use Morgan in Your Node.js Project

Logging is an essential element of writing software as it helps us to see the software operations, debug and catch errors.

Morgan is a logging tool (middleware) that can be used in HTTP servers implemented using Express & Node.js. It can be used to log requests, errors, and more to the console.

In this post, we will learn how to use Morgan in Node.js project.

Setting up Express.js Project

As Express.js is a Node.js framework, ensure you have the latest version of Node.js from Node.js before moving forward.

To include morgan in your Express project, you will need to install it as a dependency.

Create a new directory named test-morgan for your project:



mkdir test-morgan


Enter fullscreen mode Exit fullscreen mode

Change into the new directory:



cd test-morgan


Enter fullscreen mode Exit fullscreen mode

Initialize a new Node project with defaults. This will include your package.json file to access your dependencies:



npm init --yes


Enter fullscreen mode Exit fullscreen mode

Install morgan and express as a dependency:



npm install morgan express --save


Enter fullscreen mode Exit fullscreen mode

Create your entry file, index.js. This is where you will handle the logic in your Express server:



touch index.js


Enter fullscreen mode Exit fullscreen mode

Now that you’ve added morgan to your project, let’s include it in your Express server. In your index.js file, instantiate an Express instance and require morgan:



import express from 'express';
import morgan from 'morgan';
const app=express();
app.listen(3000,()=>{
console.log('Listening on port 3000...')
})


Enter fullscreen mode Exit fullscreen mode

With your Express server now set up, let’s look at using morgan to add request logging.

Getting Started With Morgan

To use morgan in your Express server, you can invoke an instance and pass it as an argument in the .use() middleware before your HTTP requests. Morgan comes with a suite of presets, or predefined format strings, to create a new logger middleware with built-in format and options. The preset tiny provides a minimal output when logging HTTP requests.

In your index.js file, call the app.use() Express middleware and pass morgan() as an argument:



app.use(morgan('tiny'));


Enter fullscreen mode Exit fullscreen mode

Now, run the express app :



node index.js


Enter fullscreen mode Exit fullscreen mode

Open your web browser and go to http://localhost:3000. You will see the following output in your web server:

morgan image 1

The output is displayed in the following format:



morgan(':method :url :status :res[content-length] - :response-time ms')


Enter fullscreen mode Exit fullscreen mode

Custom Log Formats by Creating Our Own Tokens

Tokens in morgan are functions identified following the : symbol. Morgan allows you to create your own tokens with the .token() method.

The .token() method accepts a type, or the name of the token as the first argument, following a callback function. morgan will run the callback function each time a log occurs using the token. As a middleware, morgan applies the req and res objects as arguments.

In your index.js file, employ the .token() method, and pass a type as the first argument following an anonymous function:



import express from 'express';
import morgan from 'morgan';
const app=express();
morgan.token('host', function(req, res) {
return req.hostname;
});
// we are using the host parameter
app.use(morgan(':method :host :status :res[content-length] - :response-time ms'))
app.get("/", (req, res) => {
res.send("<h1>Hello world!</h1>");
});
app.listen(3000,()=>{
console.log('Listening on port 3000...')
})


Enter fullscreen mode Exit fullscreen mode

Output:
morgan image 2
The anonymous callback function returned the hostname on the req object as a new token to use in an HTTP request in your Express server.

Designing Tokens with Custom Arguments

To denote custom arguments, you can use square brackets to define arguments passed to a token. This will allow your tokens to accept additional arguments. In your index.js file apply a custom argument to the morgan format string in the :param token:



app.use(morgan(':method :host :status :param[id] :res[content-length] - :response-time ms'));
morgan.token('param', function(req, res, param) {
return req.params[param];
});


Enter fullscreen mode Exit fullscreen mode

The custom argument id on the :param token in the morgan invocation will include the ID in the parameter following the .token() method.

Conclusion

Morgan allows flexibility when logging HTTP requests and updates precise status and response time in custom format strings or in presets. For further reading, check out the morgan documentation.

Connect with me on various platforms

Top comments (1)

Collapse
 
devland profile image
Thomas Sentre

If you just want to log HTTP requests and errors, and don't want to write extra configuration codes, Morgan is the best option.