Monitoring and Logging in MERN Stack
Last Updated :
21 Jun, 2024
Monitoring and logging are crucial for maintaining the health and performance of applications. In the MERN (MongoDB, Express.js, React, Node.js) stack, these practices help in identifying issues, ensuring application stability, and providing insights into user interactions. This article will guide you through the essentials of monitoring and logging in a MERN stack application.
Why Monitoring and Logging are Important?
- Error Tracking: Identifies and tracks errors in real time, allowing for quick resolutions.
- Performance Analysis: Monitors the performance of different components to optimize speed and efficiency.
- Security: Detects unauthorized access or suspicious activities.
- User Insights: Gathers data on user behaviour to improve the user experience.
- Compliance: Ensures that the application meets industry standards and regulations.
Approaches
There are multiple approaches to implement monitoring and logging in a MERN stack application. Here are some approaches listed below.
- Morgan: Morgan is a middleware for logging HTTP requests in Express.js applications, providing detailed logs for each request made to the server. It helps in tracking and debugging requests efficiently.
- Winston: Winston is a versatile logging library for Node.js, allowing for comprehensive and customizable logging across different transports like files, consoles, and external services. It provides detailed logs and supports various log levels for better debugging and monitoring.
- PM2: PM2 is a process manager for Node.js applications, offering features like automatic restarts, load balancing, and detailed monitoring. It helps ensure your app runs smoothly and efficiently, with real-time insights into performance and resource usage.
By implementing these approaches, you will enhance the monitoring and logging capabilities of your MERN stack application. This involves adding middleware for HTTP request logging, setting up a comprehensive logging system, and integrating a process manager. These steps will help you track performance, identify and debug issues, and ensure your application runs efficiently.
Steps to Setup Application:
Installation:
npm install winston
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple(),
}));
}
logger.info('Hello, this is an info message');
logger.error('This is an error message');
Morgan: Another popular middleware for logging HTTP requests in Express applications.
Installation:
npm install morgan
const morgan = require('morgan');
const express = require('express');
const app = express();
app.use(morgan('combined'));
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
React Logging
For client-side logging in React, you can use the loglevel
library.
Installation:
npm install loglevel
import log from 'loglevel';
log.setLevel('info');
log.info('This is an info message');
log.warn('This is a warning message');
log.error('This is an error message');
Project Structure:
Ensure You have this folder structure in your project directoryThe updated dependencies in package.json file will look like:
"dependencies": {
"loglevel": "^1.9.1",
"morgan": "^1.10.0",
"pm2": "^5.4.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"winston": "^3.13.0"
},
Example: Implementation of Logging in MERN stack.
JavaScript
import express from "express";
import morgan from "morgan"
const app = express();
// Setup morgan for logging
app.use(morgan('combined'));
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
JavaScript
// server.js
import winston from "winston";
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' })
]
});
logger.info('This is an information message');
logger.error('This is an error message');
Implementing PM2 for Node.js process management for Monitoring
PM2 is a production process manager for Node.js applications that makes it easy to manage and deploy applications in a production environment. It provides features like automatic process management, zero downtime reloads, and monitoring capabilities to ensure your Node.js applications run smoothly and efficiently.
To implement the PM2 in your website to monitoring and logging features, follow the steps listed below.
Step 1: Install the required package
npm install -g pm2
Install the package.Step 2: Start your application with PM2:
pm2 start server.js
Start your server by using this commandStep 3: View the logs:
pm2 logs
View the logs using this commandStep 4: To Monitor the application performance
pm2 monit
Monitor your application performance using this commandExample: Implementation to demonstrate how to set up basic monitoring and logging in a MERN stack application.
JavaScript
import express from 'express';
import morgan from 'morgan';
import winston from 'winston';
import mongoose from 'mongoose';
import { createServer } from 'http';
const app = express();
const port = process.env.PORT || 3000;
// Setup Morgan for request logging
app.use(morgan('combined'));
// Setup Winston for detailed logging
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' })
]
});
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mern',
{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => logger.info('Connected to MongoDB'))
.catch(err => logger.error('Could not connect to MongoDB', err));
// Basic route
app.get('/', (req, res) => {
res.send('Hello World');
logger.info('Hello World route accessed');
});
// Start the server
createServer(app).listen(port, () => {
logger.info(`Server running on port ${port}`);
});
Output: To see the logging and monitoring in action, start your server and access the routes. Use pm2 logs to view real-time logs in your terminal.
This is the output for monitoring the application performance.Best Practices
- Log Levels: Use different log levels (info, warn, error) to differentiate the importance of logs.
- Log Rotation: Implement log rotation to manage log file sizes and avoid disk space issues.
- Sensitive Information: Avoid logging sensitive information like passwords or personal data.
- Structured Logging: Use JSON format for logs to make it easier to parse and analyze.
- Monitor Key Metrics: Track important metrics like response time, CPU usage, memory usage, and error rates.
- Alerts: Set up alerts for critical issues that require immediate attention.
Conclusion
Effective monitoring and logging are essential for maintaining the reliability and performance of a MERN stack application. By using tools like Winston, Morgan, PM2, Sentry, and Google Analytics, developers can gain valuable insights, quickly identify and resolve issues, and ensure a smooth user experience. Implement these practices and tools to keep your application running smoothly and efficiently.
References:
To know more about MERN Stack, Click here.
Similar Reads
Monitoring and Logging in Spring Boot
Spring Boot is one of the most popular application development frameworks among developers. Spring boot can be used to develop standalone Java enterprise-level applications. Spring framework also provides features for ease of development and better security and performance in spring applications. Th
6 min read
Monitoring and Logging for Reactive Applications
Reactive applications are designed to be responsive, resilient, elastic, and message-driven. Monitoring and logging are the crucial aspects of maintaining and troubleshooting these applications. They can provide insights into the application performance, help detect issues early, and ensure smooth o
5 min read
Working with Monitoring and Logging Services
Pre-requisite: Google Cloud Platform Monitoring and Logging services are essential tools for any organization that wants to ensure the reliability, performance, and security of its systems. These services allow organizations to collect and analyze data about the health and behavior of their systems,
5 min read
Monitoring And Logging For Amazon ECS Services
As we all know monitoring and logging are crucial to managing ECS services effectively. In this article, we will explore the different ways to set up monitoring and logging for ECS services. Meanwhile, we will ensure some of the important chords like optimal performance, troubleshoot issues, and gai
4 min read
Monitoring Model Training in PyTorch with Callbacks and Logging
Monitoring model training is crucial for understanding the performance and behavior of your machine learning models. PyTorch provides several mechanisms to facilitate this, including the use of callbacks and logging. This article will guide you through the process of using these tools effectively. T
7 min read
Express Routing in MERN Stack
Express is a powerful framework for building web applications and APIs in NodeJS. When integrated into the MERN (MongoDB, Express, React, Node.js) stack, Express handles server-side routing and provides a robust foundation for handling HTTP requests and responses. In this article, we will explore ho
3 min read
Monitoring and Logging in Spring Cloud Config Server
In Microservices, Spring Cloud Server can play a crucial role in Spring microservices by providing centralized configuration management. It helps externalize configuration properties across all environments for applications, making them easier to manage and update without redeploying or restarting t
9 min read
Amazon DynamoDB - Logging & Monitoring DynamoDB
Logging is the collection of all the data from cloud services, infrastructure, and applications. It helps in identifying issues, measure performance, and configurations. Whereas monitoring is helpful to detect possible breaches, security gaps and secure the network well before the attack happens. If
2 min read
What is API Monitoring in Postman ?
API Monitoring is a process that monitors the activity, output, and performance of an API based on Environment, Time, regions, etc. API monitoring plays a significant role in identifying and addressing issues related to API functionality and security before they impact partners or end-users of that
6 min read
Swagger and API Monitoring
API monitoring is like having a watchful guardian for your digital communication paths, playing a big role in making software work well. It keeps an eye on how things are going, manages mistakes, makes sure everything responds quickly, checks everything in real-time, makes the user experience better
6 min read