Logging Middleware for Express

In an Express application, you can create middleware to log HTTP requests and responses.

const express = require('express');
const winston = require('winston');

const app = express();

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console()
  ]
});

app.use((req, res, next) => {
  logger.info('HTTP Request', {
    method: req.method,
    url: req.url,
    headers: req.headers
  });
  res.on('finish', () => {
    logger.info('HTTP Response', {
      statusCode: res.statusCode,
      statusMessage: res.statusMessage
    });
  });
  next();
});

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *