Programming like a "backend engineer" in Node, Express applications.
Node.js and Express are popular technologies for building web applications, providing developers with the tools needed to create fast and scalable backends. Two modules that can help with debugging and logging in these applications are Morgan and Debug.
Morgan is an HTTP request logger middleware for Node.js that logs details about each request, such as the HTTP method, URL, status code, and response time. Debug, on the other hand, is a small debugging utility module that allows developers to log messages to the console with different levels of severity.
In this tutorial, we'll cover how to use both modules in a Node.js or Express project.
Installing Morgan and Debug
Before we can start using Morgan and Debug, we need to install them. Open up your terminal and navigate to the project directory. Then, run the following command:
npm install morgan debug
This command will install both the Morgan and Debug modules.
Using Morgan for Logging http Requests
To use Morgan, we need to require it in our Node.js or Express application. Here's an example of how to use it in an Express app:
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('dev'));
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
In this code, we require the Morgan module and then use it as middleware for our Express app by calling app.use(morgan('dev'))
. This will log each HTTP request to the console with the "dev" format, which includes the HTTP method, URL, status code, and response time.
Using Debug for Debugging Messages
Debug is a small debugging utility that allows us to log messages to the console with different levels of severity. Here's an example of how to use it in a Node.js application:
const debug = require('debug')('my-app');
debug('Starting server...');
// Do some work...
debug('Server started on port 3000');
In this code, we require the Debug module and then create a new debug logger with the name "my-app" by calling require('debug')('my-app')
. We can then use this logger to log messages to the console with the debug
function, which takes a message string as its argument.
By default, Debug will only log messages if the DEBUG
environment variable is set to a value that matches the logger name. For example, if we set the DEBUG
environment variable to my-app
, Debug will log our messages to the console.
Conclusion
Morgan and Debug are useful tools for logging and debugging in Node.js and Express applications. With Morgan, we can easily log HTTP requests and responses, while Debug allows us to log messages with different levels of severity. By using these modules, we can quickly identify and fix issues in our applications.