How to Use Morgan in Your Node.js Project
Tags: webdev, javascript, beginners, node
Published: 2023-01-07 10:31:18

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
```
Change into the new directory:

```
cd test-morgan
```
Initialize a new Node project with defaults. This will include your _package.json_ file to access your dependencies:

```
npm init --yes
```
Install morgan and express as a dependency:

```
npm install morgan express --save
```
Create your entry file, _index.js_. This is where you will handle the logic in your Express server:

```
touch index.js
```
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:

```javascript
import express from 'express';
import morgan from 'morgan';
const app=express();
app.listen(3000,()=>{
console.log('Listening on port 3000...')
})
```
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:

```javascript
app.use(morgan('tiny'));
```
Now, run the express app :

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

![morgan image 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lda7j27iysljlful2688.jpg)

The output is displayed in the following format:

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

## 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:

```javascript
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...')
})
```
Output:
![morgan image 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/216pr0xhpaa7mf9k6y8s.jpg)
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:

```javascript
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];
});
```
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](https://github.com/expressjs/morgan#readme).

Connect with me on [various platforms](https://bio.link/thomassentre)