Open In App

Monitoring and Logging in MERN Stack

Last Updated : 21 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

monitorLogingeeks
Ensure You have this folder structure in your project directory

The 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
pgm2geeks
Install the package.

Step 2: Start your application with PM2:

pm2 start server.js
startpm2geeks-min
Start your server by using this command

Step 3: View the logs:

pm2 logs
pm2logsgeeks-min
View the logs using this command

Step 4: To Monitor the application performance

pm2 monit
monitorpm2geeks-min
Monitor your application performance using this command

Example: 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.

monitorpm2geeks-min
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.


Next Article
Article Tags :

Similar Reads