📋 3.12. Logging & Monitoring – Tracking Application Health

Table of Contents

🤔 “Why is my app crashing?”
😫 “Where did that error come from?”
😵‍💫 “Is my app running slow for some users?”

These are questions every developer faces — even the pros.

That’s where logging and monitoring come in 💡.

It’s like giving your app a health checkup 🩺, so you can catch bugs, measure performance, and sleep peacefully at night 🛏️.

Let’s break it down in a fun, friendly way — like I’m teaching my little cousin!


🚀 What Is Logging & Monitoring?

📜 Logging

Logging is like writing a diary 📓 for your app.
It records what happens — good or bad.

Example:
“User logged in at 3:14 PM”
“Error: Database connection failed ❌”

🛰️ Monitoring

Monitoring is like checking your app’s heart rate in real-time ❤️‍🔥.
It tells you:

  • How much memory your app is using
  • If a process is stuck
  • How many users are online

🎯 Why You Need It (Yes, You!)

ReasonLoggingMonitoring
Debug errors 🐛
Check performance 📈
Track activity 📚
Keep app healthy 🩺

Logging + Monitoring = A happy, healthy, maintainable app! 🎉


🛠️ Tools We’ll Use

ToolUse
MorganHTTP request logger 📡
WinstonAdvanced logging engine 📓
PM2Process and performance monitor 🧠

We’ll use them together in a Node.js + Express setup.


🧱 Step-by-Step Logging with Morgan

1️⃣ Install Morgan

bashCopyEditnpm install morgan

2️⃣ Use It in Express App

jsCopyEditconst express = require('express');
const morgan = require('morgan');
const app = express();

app.use(morgan('tiny')); // or 'combined' for detailed logs

app.get('/', (req, res) => {
  res.send('Hello from Web Codder! 🎉');
});

app.listen(3000, () => console.log('Server running 🚀'));

Now every request (GET, POST, etc.) is logged like:

sqlCopyEditGET / 200 12ms - 150B

Super helpful for debugging slow routes or API misuse!


🧱 Structured Logging with Winston

1️⃣ Install Winston

bashCopyEditnpm install winston

2️⃣ Create a Logger File

jsCopyEdit// logger.js
const { createLogger, transports, format } = require('winston');

const logger = createLogger({
  level: 'info',
  format: format.combine(
    format.timestamp(),
    format.json() // logs as structured JSON
  ),
  transports: [
    new transports.Console(),
    new transports.File({ filename: 'logs/error.log', level: 'error' }),
    new transports.File({ filename: 'logs/combined.log' })
  ],
});

module.exports = logger;

3️⃣ Use Logger in App

jsCopyEditconst logger = require('./logger');

app.get('/test', (req, res) => {
  logger.info('Test route accessed ✅');
  res.send('Logging works!');
});

app.get('/fail', (req, res) => {
  logger.error('Something went wrong 😢');
  res.status(500).send('Error!');
});

Now your logs are organized by type and saved to files! 📁


🔢 Logging Levels Explained

LevelUse Case
errorCritical problems 🔥
warnPotential issues ⚠️
infoRegular activity 📝
debugDevelopment logs 🧪

Set different levels for dev and production 🔧.


📈 Real-Time Monitoring with PM2

1️⃣ Install PM2 Globally

bashCopyEditnpm install pm2 -g

2️⃣ Start Your App with PM2

bashCopyEditpm2 start app.js

Now PM2 keeps your app alive, even if it crashes!

3️⃣ View Logs & Status

bashCopyEditpm2 logs           // view live logs
pm2 list           // show all running apps
pm2 monit          // real-time dashboard 📊

4️⃣ Auto-Restart on Server Reboot

bashCopyEditpm2 startup
pm2 save

💡 Bonus: You can deploy multiple apps and scale them with PM2!


📊 Infographic (Insert Placeholder)

Orig
📋 3.12. Logging & Monitoring - Tracking Application Health 2


🧠 Pro Tips

  • ✅ Use Morgan for quick request tracking
  • ✅ Use Winston for deep debugging and file logs
  • ✅ Use PM2 for real-time monitoring and zero-downtime restarts
  • 🚫 Don’t log passwords or sensitive info!
  • 🔐 Log only what you need in production to avoid bloated files

🔚 Conclusion: Keep Your App Healthy 🏥

Logging and monitoring are like having a doctor + bodyguard for your app.

They:

  • Help you fix bugs faster 🐞
  • Make your app more stable ⚙️
  • Give you peace of mind at night 🌙

📣 Love Learning This Way?

Then you’ll love what’s coming next! 🧑‍💻

Stay sharp, code smart, and track everything 🧠🚀

Share the Post:
Picture of Web Codder

Web Codder

Vikas Sankhla is a seasoned Full Stack Developer with over 7 years of experience in web development. He is the founder of Web Codder, a platform dedicated to providing comprehensive web development tutorials and resources. Vikas specializes in the MERN stack (MongoDB, Express.js, React.js, Node.js) and has been instrumental in mentoring aspiring developers through his online courses and content. His commitment to simplifying complex web technologies has made him a respected figure in the developer community.

Related Posts