Learn Express.js · 12/14

Logging and Monitoring

7 min read

Imagine you are managing a massive hotel (the server). Guests (requests) arrive, check into rooms, request room service, and occasionally break a lamp. If you do not have a guest registry or security cameras, and a room catches fire at 3:00 AM, you will have absolutely no idea who started it, when it happened, or how to prevent it tomorrow.

In software, a server running blindly without keeping records is a disaster waiting to happen. You need a reliable way to record events (logging) and check if the hotel is still standing (monitoring).


1. The Importance of Application Logging in Production 🚨

Problem: While developing on your laptop, if an error happens, you just look at your terminal. But when your Express app is deployed to a server farm in Ohio and serves thousands of users per minute, you cannot simply stare at a live terminal. If a user in Tokyo experiences a crash, how do you know what went wrong?

Definition: Application logging is the practice of recording events, errors, and system state as your application runs. In production environments, these records (logs) are the only source of truth for debugging, auditing, and analyzing user behavior.

Why does it matter?

  • Post-Mortem Debugging: When your app crashes, logs provide the stack trace and the exact sequence of events that led to the crash.
  • Security & Auditing: Logs tell you if someone is trying to brute-force a login endpoint.
  • Performance Metrics: Logs can record how long a database query took, helping you find bottlenecks.

Industry Reality: Developers rarely look at logs when everything is fine. You will usually be staring at them with bloodshot eyes at 3:00 AM when the production server is down. Relying entirely on console.log("here 1") and console.log("here 2") is not an industry standard. console.log is often synchronous, blocks the main thread in certain environments, and lacks context (like timestamps or severity levels).


2. Basic Request Logging with Morgan 🕵️‍♂️

Problem: You need to know which endpoints are being called, what the response status codes are, and how long they take to resolve. Adding a log statement inside every single one of your hundreds of route handlers is repetitive, error-prone, and violates the DRY (Don't Repeat Yourself) principle.

Definition: Morgan is an HTTP request logger middleware for Node.js. It automatically intercepts incoming requests and logs their details before passing them further down the Express middleware chain.

The Flow: Imagine a bouncer standing at the door of a club holding a clipboard. Every time someone walks in or out, the bouncer writes down their ID, entry time, and whether they were allowed in. Morgan is that bouncer for your HTTP requests.

Installation

bash
npm install morgan

Industry Standard Usage

In the industry, Morgan is typically used with two main pre-defined formats: dev for local development (colorful, concise) and combined for production (standard Apache combined log output, which includes IP addresses, user agents, and exact dates).

javascript
const express = require('express');
const morgan = require('morgan');

const app = express();

// Use 'dev' format for local development
// Outputs: GET /api/users 200 15.421 ms - 245
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}

// Use 'combined' format for production
// Outputs: ::1 - - [25/Feb/2026:05:58:00 +0000] "GET /api/users HTTP/1.1" 200 245 "-" "Mozilla/5.0..."
if (process.env.NODE_ENV === 'production') {
  app.use(morgan('combined'));
}

app.get('/api/users', (req, res) => {
  res.json({ message: "Users fetched successfully!" });
});

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

Under the hood: Morgan hooks into Node's native HTTP res.on('finish') event. This is why it knows exactly how long the request took and what the final status code was, even though you place it at the very top of your middleware stack.


3. Advanced Application Logging with Pino 🌲

Problem: Morgan is great for HTTP requests, but what about application logic? When a database fails to connect, or a background payment process completes, you need to log that. As mentioned, console.log is a performance bottleneck in Node.js and outputs unstructured text that is difficult for modern log aggregators (like Datadog, AWS CloudWatch, or Splunk) to search through.

Definition: Pino is a very low overhead, modern Node.js logger. It outputs logs in JSON format. JSON logs are structured, meaning machines can easily parse them to filter logs by severity level, user ID, or timestamp. (Note: Winston is another popular choice, but Pino has largely become the modern industry standard due to its speed).

How it solves the problem: By outputting JSON, your log aggregator can instantly filter out all logs where level: "error", instead of you manually searching through millions of lines of text looking for the word "Error". Furthermore, Pino handles logging asynchronously, meaning it won't slow down your Express app.

Installation

We install pino for production, and pino-pretty to make the JSON logs human-readable on our local machines.

bash
npm install pino
npm install pino-pretty --save-dev

Industry Standard Setup

javascript
const pino = require('pino');

// Create a logger instance
// If in development, format it nicely. In production, leave it as fast JSON.
const isDev = process.env.NODE_ENV !== 'production';

const logger = pino({
  level: process.env.LOG_LEVEL || 'info',
  ...(isDev && {
    transport: {
      target: 'pino-pretty',
      options: { colorize: true }
    }
  })
});

// Usage Example
logger.info('Server is starting up...');

const processPayment = (amount) => {
  if (amount < 0) {
    // Using levels: error, warn, info, debug, trace
    logger.error({ amount }, 'Attempted to process a negative payment amount');
    return false;
  }
  logger.info({ amount, currency: 'USD' }, 'Payment processed successfully');
  return true;
};

processPayment(150);
processPayment(-50);

Log Levels:
Industry practice dictates strict adherence to log levels:

  • ERROR: Something failed. The app cannot perform a function (e.g., Database connection dropped). Usually triggers an alert to a developer's phone.
  • WARN: Something unexpected happened, but the app recovered (e.g., An API rate limit was hit, so we retried).
  • INFO: General system state (e.g., Server started, batch job finished).
  • DEBUG: Highly detailed information used only by developers while fixing bugs. Turned off in production to save disk space.

4. Creating Health Check Endpoints for Uptime Monitoring 🩺

Problem: When you deploy your application to modern cloud environments (like Kubernetes, AWS ECS, or Render), the platform running your app needs to know if it is actually working. Sometimes an Express app gets deadlocked (frozen) or loses connection to the database. The server is technically "running," but it's not serving requests properly.

Definition: A Health Check Endpoint is a dedicated route (usually /health or /status) that external monitoring tools ping continuously (e.g., every 10 seconds) to verify that the application is responsive and its core dependencies are functional.

The Flow: Imagine a supervisor poking an employee every 10 minutes and asking, "Are you awake?" If the employee replies "Yes," the supervisor walks away. If the employee doesn't reply, or says "I'm having a heart attack," the supervisor immediately calls for a replacement.

Industry Standard Implementation

A basic health check just verifies the Express event loop isn't blocked. An advanced health check also verifies database connectivity.

javascript
const express = require('express');
const app = express();

// Basic Health Check
app.get('/health', (req, res) => {
  const healthCheck = {
    uptime: process.uptime(), // How many seconds the server has been running
    message: 'OK',
    timestamp: Date.now()
  };
  
  try {
    // If everything is fine, send 200 OK
    res.status(200).json(healthCheck);
  } catch (error) {
    // If something critical fails, send 503 Service Unavailable
    healthCheck.message = error.message;
    res.status(503).json(healthCheck);
  }
});

app.listen(3000, () => {
  console.log('App running on port 3000');
});

Status Code Importance: Notice the 503 Service Unavailable. If your application returns a 500-level error to a load balancer or a container orchestrator like Kubernetes, the orchestrator will automatically stop sending user traffic to this specific server instance and will usually restart it. This self-healing architecture entirely relies on your /health endpoint telling the truth!


References & Extra Reading 📚

Challenge

Challenge Instructions

Your task is to build a small but robust Express.js server that incorporates industry-standard practices for logging and health monitoring.

  1. Setup: Require the express, morgan, and pino modules.
  2. Logger Initialization: Instantiate a pino logger.
  3. HTTP Request Logging: Configure the application to use the morgan middleware. It must be set up to use the combined log format, which is standard for production environments.
  4. Application-Level Logging:
    • Create a root route GET / that responds with a simple JSON message {"message": "Welcome!"}. Within this route, use your pino logger to log an info level message containing the string "Root endpoint was accessed".
    • Create another route GET /error that simulates a failure. This route should respond with a 500 status code and a JSON message {"error": "Simulated internal server error"}. Before sending the response, use your pino logger to log an error level message. The log entry must include a custom object { eventId: 'user-action-failed', details: 'Database connection timed out' } as part of the log.
  5. Health Check Endpoint: Implement a GET /health endpoint. This endpoint must respond with a 200 OK status code and a JSON body of {"status": "UP", "timestamp": "<current_iso_string>"}. The timestamp should be the current time in ISO 8601 format.
  6. Server Startup: Make the application listen on port 3000. In the listen callback, replace the standard console.log with your pino logger to log an info message indicating that the server has started and is listening on the correct port.

Expected result

Your final code should be a complete and runnable Express.js application script. The script must successfully:

  1. Import and initialize express, morgan, and pino.
  2. Correctly apply the morgan middleware to the Express app using the combined format string.
  3. Define a GET / route that uses the pino instance's info() method for logging.
  4. Define a GET /error route that uses the pino instance's error() method, including the specified custom object in the log call.
  5. Define a GET /health route that returns a 200 status and the correct JSON payload, dynamically generating the ISO timestamp.
  6. Start the server on port 3000, using the pino instance's info() method in the listen callback instead of console.log.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.