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.
Before you begin, ensure that you have the following:
npx create-next-app@latest.winston is a versatile and popular logging library in the Node.js ecosystem. It supports various transports, formats, and levels of logging.
First, install the necessary packages:
npm install winston winston-daily-rotate-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;
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>
);
}
morgan is a popular HTTP request logger middleware for Node.js. It helps you log incoming requests and can be integrated with winston.
Install morgan using npm:
npm install morgan
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');
});
});
Start your Next.js application and access some pages. You should see logs in both the console and the log files.
info, warn, error) to categorize your logs.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.