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

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

Setting Up Logging

Updated 2026-04-20
2 min read

Introduction

Logging is an essential part of any application's lifecycle, providing insights into its behavior and helping developers diagnose issues. In this tutorial, we will explore how to set up logging in a Next.js application using popular tools like winston for structured logging and morgan for HTTP request logging.

Prerequisites

Before you begin, ensure that you have the following:

  • A basic understanding of Next.js.
  • Node.js installed on your machine.
  • An existing Next.js project or create a new one using npx create-next-app@latest.

Setting Up Winston for Structured Logging

winston is a versatile and popular logging library in the Node.js ecosystem. It supports various transports, formats, and levels of logging.

Step 1: Install Winston

First, install the necessary packages:

npm install winston winston-daily-rotate-file

Step 2: Create a Logger Configuration File

Create a new file named logger.js in your project's root directory. This file will contain the configuration for our logger.

// logger.js
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, printf, json } = format;
const DailyRotateFile = require('winston-daily-rotate-file');

// Define a custom log format
const myFormat = printf(({ level, message, timestamp }) => {
  return `${timestamp} ${level}: ${message}`;
});

// Create the logger instance
const logger = createLogger({
  level: 'info',
  format: combine(
    timestamp(),
    json()
  ),
  transports: [
    // Write all logs with level `error` and below to `error.log`
    new DailyRotateFile({
      filename: 'logs/error-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      zippedArchive: true,
      maxSize: '20m',
      maxFiles: '14d'
    }),
    // Write all logs with level `info` and below to `combined.log`
    new DailyRotateFile({
      filename: 'logs/combined-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      zippedArchive: true,
      maxSize: '20m',
      maxFiles: '14d'
    })
  ]
});

// If we're not in production then log to the `console` with the format:
if (process.env.NODE_ENV !== 'production') {
  logger.add(new transports.Console({
    format: combine(
      timestamp(),
      myFormat
    )
  }));
}

module.exports = logger;

Step 3: Use the Logger in Your Application

You can now use this logger throughout your Next.js application. For example, add logging to a page:

// pages/index.js
import logger from '../logger';

export default function Home() {
  useEffect(() => {
    logger.info('Home page accessed');
  }, []);

  return (
    <div>
      <h1>Welcome to the Home Page</h1>
    </div>
  );
}

Setting Up Morgan for HTTP Request Logging

morgan is a popular HTTP request logger middleware for Node.js. It helps you log incoming requests and can be integrated with winston.

Step 1: Install Morgan

Install morgan using npm:

npm install morgan

Step 2: Configure Morgan to Use Winston

Modify your server entry point (usually server.js or the default Next.js setup) to use morgan with winston.

// server.js
const express = require('express');
const next = require('next');
const morgan = require('morgan');
const logger = require('./logger');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  // Use morgan with winston
  server.use(morgan('combined', { stream: { write: (message) => logger.info(message.trim()) } }));

  server.get('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(3000, (err) => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});

Step 3: Test Your Setup

Start your Next.js application and access some pages. You should see logs in both the console and the log files.

Best Practices for Logging

  1. Use Structured Logging: Always use structured logging (e.g., JSON) to make it easier to parse and analyze logs.
  2. Log Levels: Use appropriate log levels (info, warn, error) to categorize your logs.
  3. Environment-Specific Logging: Adjust logging verbosity based on the environment (development, staging, production).
  4. Secure Sensitive Information: Avoid logging sensitive information such as passwords or API keys.
  5. Centralized Logging: Consider using a centralized logging service like ELK Stack, Splunk, or AWS CloudWatch for better log management and analysis.

Conclusion

Setting up logging in your Next.js application is crucial for monitoring and debugging. By following this guide, you have integrated winston for structured logging and morgan for HTTP request logging. This setup will help you gain insights into your application's behavior and troubleshoot issues effectively.


PreviousLogging and MonitoringNext Monitoring Tools (e.g., Sentry, New Relic)

Recommended Gear

Logging and MonitoringMonitoring Tools (e.g., Sentry, New Relic)