![]() |
VOOZH | about |
Morgan is a popular HTTP request logger middleware for Node.js. It simplifies the process of logging HTTP requests in a Node.js application by automatically generating logs for incoming requests. Morgan provides various logging formats and options, allowing developers to customize the logging output according to their requirements.
Here's a breakdown of key aspects of Morgan:
combined, common, dev, short, and tiny. These formats determine the structure and content of the generated logs. Additionally, developers can create custom logging formats tailored to their specific needs.Step 1: Create a new folder for a project using the following command:
mkdir morganStep 2: Navigate to our folder using the following command:
cd morganStep 3: Initialize npm using the following command and server file:
npm init -y
touch index.js
Step 4: Install required packages using the following command:
npm i express morganThe updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.19.2",
"morgan": "^1.10.0"
}
Example 1: Implementation to Use dev as a preset in morgan.
Steps to run: Run the application using the following command.
node index.jsOutput: To send the request, We use a browser, That request will be logged by our logger morgan.
👁 ImageThen we will see the following output in our console.
Explanation: Basically in the above code, we set up morgan, and since it's a middleware, So we used the .use() method to tell express to use that as a middleware in our app. Other than that we have used 'dev' as a preset. Some other presets available are combined, common, short, tiny. Each preset returns different information.
Example 2: In this example tiny is used as a preset inside morgan instead of dev.
Steps to run: Run the application using the following command.
node index.jsOutput: To send the request, We use a browser, That request will be logged by our logger morgan.
👁 ImageThen we will see the following output in our console.
👁 ImageExplanation: In this 304 code is there, the Reason is since it is a simple static webpage, So browser cached it and returned its previous instance instead of making a new request.
Morgan simplifies the process of logging HTTP requests in Node.js applications, providing developers with valuable insights into application traffic and aiding in debugging and monitoring efforts. Its customizable logging formats and seamless integration with Express.js make it a popular choice among Node.js developers for HTTP request logging.