In any application, logging is a crucial aspect of monitoring and debugging. It helps developers understand the flow of their applications, identify issues, and maintain robust systems. For Node.js applications built with Express.js, two popular logging libraries are Morgan and Winston. Morgan is great for HTTP request logging, while Winston provides more comprehensive logging capabilities.
In this tutorial, we'll explore how to set up both Morgan and Winston in an Express application to enhance your application's monitoring and debugging process.
Morgan is a middleware that logs details about HTTP requests to the console. It's lightweight and easy to use, making it ideal for basic logging needs. Morgan provides several predefined formats like combined, common, dev, etc., which can be used directly or customized further.
Winston is a more advanced logging library that supports multiple transports (like file, console, HTTP), custom log levels, and even integrates with various external services for centralized logging. It's highly configurable and suitable for applications requiring detailed and structured logs.
Let's set up both Morgan and Winston in an Express application step by step.
First, create a new directory for your project and initialize it using npm:
mkdir express-logger && cd express-loggernpm init -y
Install Express.js, Morgan, and Winston along with their required packages:
Make a GET request to http://localhost:3000/. You should see logs in both the console and the rotating log files.
2023-10-05T14:48:00.000Z info GET request to / endpoint ::ffff:127.0.0.1 - - [05/Oct/2023:14:48:00 +0000] "GET / HTTP/1.1" 200 12 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36"
Now that you have set up logging using Morgan and Winston in your Express application, the next step is to explore Performance Monitoring with New Relic. This will help you gain deeper insights into how your application performs under various conditions.
Stay tuned for more tutorials on advanced monitoring and optimization techniques!