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:
import express from 'express';
import morgan from 'morgan';
const app=express();
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:
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:
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:
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:
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];
});
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.
THANK YOU FOR READING
I hope you found this little article helpful. Please share it with your friends and colleagues. Sharing is caring. Connect with me on Twitter or LinkedIn to read more about JavaScript, React, Node.js, and more…!Want to work together? Contact me on Upwork!