myHotTake

Tag: application monitoring

  • How to Log and Monitor Node.js Apps Effectively?

    If you find this story helpful, feel free to like or share!


    I’m a sailor navigating the ocean. My Node.js application is my sturdy ship, and I have a set of tools to ensure my journey is smooth and my ship stays afloat. Logging and monitoring are like my compass and telescope—essential for keeping my course steady and spotting potential storms on the horizon.

    As I set sail, I equip my ship with a compass, which is akin to using Winston or Bunyan for logging. These tools record the ship’s journey, noting every significant event, much like logging important actions and errors in my application. When I encounter rough seas, the compass helps me understand what went wrong and how to adjust my course.

    Now, think of my telescope as my monitoring tools, such as Prometheus, Grafana, or New Relic. With it, I can scan the horizon, watching for changes in the weather—much like keeping an eye on the performance and health of my application. These tools provide real-time insights, alerting me to potential performance bottlenecks or resource usage spikes before they become full-fledged storms.

    As I journey across the ocean, the interplay between my compass and telescope ensures I stay on track. My logs tell the story of where I’ve been, while my monitoring tools help me anticipate where I’m headed. Together, they form a crucial navigational system that keeps my Node.js application shipshape, allowing me to focus on discovering new lands and making my voyage a success.

    And so, as I sail my digital seas, I know that with the right tools in hand, I can weather any storm and keep my Node.js application on a steady course.


    Logging with Winston

    To use Winston as my compass, I first need to install it:

    npm install winston

    Now, I set up Winston to log important events:

    const winston = require('winston');
    
    const logger = winston.createLogger({
      level: 'info',
      format: winston.format.json(),
      transports: [
        new winston.transports.Console(),
        new winston.transports.File({ filename: 'combined.log' })
      ]
    });
    
    // Logging an info message
    logger.info('Sailing smoothly across the ocean.');
    
    // Logging an error
    logger.error('Encountered a storm! Adjusting course.');

    With this setup, I can easily track the journey of my application, noting both the ordinary and extraordinary events that occur.

    Monitoring with Prometheus and Grafana

    For monitoring, I use Prometheus and Grafana to keep an eye on my application’s performance, much like a telescope scanning the horizon. Here’s how I might set it up:

    First, I need to integrate Prometheus in my Node.js app, typically using a library like prom-client:

    npm install prom-client

    Then, I set up some basic metrics:

    const promClient = require('prom-client');
    
    // Create a Registry which registers the metrics
    const register = new promClient.Registry();
    
    // Add a default label which is added to all metrics
    register.setDefaultLabels({
      app: 'my-nodejs-app'
    });
    
    // Enable the collection of default metrics
    promClient.collectDefaultMetrics({ register });
    
    // Create a custom metric
    const requestCounter = new promClient.Counter({
      name: 'request_count',
      help: 'Total number of requests',
      registers: [register]
    });
    
    // Increment the counter on each request
    app.use((req, res, next) => {
      requestCounter.inc();
      next();
    });
    
    // Expose the metrics at the /metrics endpoint
    app.get('/metrics', (req, res) => {
      res.set('Content-Type', register.contentType);
      res.end(register.metrics());
    });

    Now, Prometheus can scrape these metrics, and I can visualize them in Grafana, keeping a vigilant watch over my application’s performance.

    Key Takeaways

    • Logging with Winston: Acts as the compass, providing detailed logs of application events and errors, helping in troubleshooting and understanding application flow.
    • Monitoring with Prometheus and Grafana: Functions as the telescope, offering real-time insights into application performance and resource usage, allowing proactive management.
    • Integration: Combining logging and monitoring provides a comprehensive view of application health, ensuring smooth sailing in production environments.