codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
▲

Next.js

62 / 73 topics
62Logging and Monitoring63Setting Up Logging64Monitoring Tools (e.g., Sentry, New Relic)
Tutorials/Next.js/Logging and Monitoring
▲Next.js

Logging and Monitoring

Updated 2026-04-20
3 min read

Logging and Monitoring in Next.js

Introduction

In modern web development, logging and monitoring are crucial for maintaining application health, diagnosing issues, and ensuring performance. This section will guide you through setting up effective logging and monitoring strategies using Next.js.

Why Logging and Monitoring?

  • Error Detection: Quickly identify and resolve errors.
  • Performance Optimization: Monitor response times and resource usage.
  • Security Auditing: Track suspicious activities and potential security breaches.
  • User Experience: Ensure that your application is running smoothly for users.

Setting Up Logging

1. Choose a Logging Library

For Next.js, popular logging libraries include:

  • Winston: A versatile logging library with various transports.
  • Pino: Known for its speed and minimal overhead.
  • Log4js: Offers flexible configuration options.

We'll use Winston in this tutorial due to its extensive features and community support.

2. Install Winston

First, install Winston using npm or yarn:

npm install winston

or

yarn add winston

3. Configure Winston

Create a logger.js file in your project root to configure Winston:

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

const logger = createLogger({
  level: 'info',
  format: format.combine(
    format.timestamp(),
    format.errors({ stack: true }),
    format.splat(),
    format.json()
  ),
  defaultMeta: { service: 'user-service' },
  transports: [
    new transports.File({ filename: 'error.log', level: 'error' }),
    new transports.File({ filename: 'combined.log' })
  ]
});

if (process.env.NODE_ENV !== 'production') {
  logger.add(new transports.Console({
    format: format.simple()
  }));
}

module.exports = logger;

4. Use the Logger in Your Application

Import and use the logger in your Next.js pages or API routes:

// pages/api/hello.js
import logger from '../../logger';

export default function handler(req, res) {
  try {
    // Simulate an error
    if (req.query.error) throw new Error('Simulated error');
    
    logger.info('Request received', { method: req.method, url: req.url });
    res.status(200).json({ message: 'Hello World!' });
  } catch (error) {
    logger.error(error.message, { stack: error.stack });
    res.status(500).json({ error: 'Internal Server Error' });
  }
}

Setting Up Monitoring

1. Choose a Monitoring Service

Popular monitoring services for Next.js include:

  • New Relic: Offers comprehensive APM and logging.
  • Datadog: Provides real-time performance monitoring.
  • Prometheus + Grafana: Open-source solution for metrics collection and visualization.

We'll use Prometheus with Grafana for this tutorial due to their open-source nature and flexibility.

2. Install Prometheus

First, download and install Prometheus:

wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz
tar xvfz prometheus-2.30.3.linux-amd64.tar.gz
cd prometheus-2.30.3.linux-amd64

3. Configure Prometheus

Edit the prometheus.yml file to scrape metrics from your Next.js application:

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'nextjs'
    static_configs:
      - targets: ['localhost:3000']

4. Install and Configure Grafana

Install Grafana using Docker for simplicity:

docker run -d -p 3000:3000 --name grafana grafana/grafana

Access Grafana at http://localhost:3000 (default login is admin/admin).

5. Set Up Dashboards

  1. Add Prometheus as a Data Source:

    • Go to Configuration > Data Sources.
    • Click "Add data source" and select Prometheus.
    • Enter the URL http://host.docker.internal:9090.
  2. Create a Dashboard:

    • Click on the "+" icon and select "Dashboard".
    • Add panels for metrics like response time, error rates, etc.

Best Practices

  • Log Levels: Use appropriate log levels (info, warn, error) to categorize logs.
  • Structured Logging: Log in JSON format for easier parsing and analysis.
  • Environment-Specific Logging: Adjust logging verbosity based on the environment (development, staging, production).
  • Secure Sensitive Information: Avoid logging sensitive data such as passwords or personal information.

Conclusion

Logging and monitoring are essential components of any robust application. By integrating Winston for logging and Prometheus with Grafana for monitoring in your Next.js projects, you can gain valuable insights into your application's performance and health. This setup will help you quickly identify issues and optimize your application for better user experience and reliability.


PreviousGlobal Error BoundaryNext Setting Up Logging

Recommended Gear

Global Error BoundarySetting Up Logging