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.
For Next.js, popular logging libraries include:
We'll use Winston in this tutorial due to its extensive features and community support.
First, install Winston using npm or yarn:
npm install winston
or
yarn add 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;
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' });
}
}
Popular monitoring services for Next.js include:
We'll use Prometheus with Grafana for this tutorial due to their open-source nature and flexibility.
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
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']
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).
Add Prometheus as a Data Source:
http://host.docker.internal:9090.Create a Dashboard:
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.