How to use Morgan in Node.js

Morgan provides automated HTTP request logging for Express applications, capturing essential information about incoming requests and responses for monitoring and debugging. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented Morgan logging in Node.js production services throughout my 11 years of backend development. The most practical approach is installing morgan and configuring it as Express middleware with predefined or custom formats. This method enables comprehensive request tracking with minimal configuration and supports writing logs to files for production environments.

Install morgan package, configure as Express middleware with desired format for automatic HTTP request logging.

const express = require('express')
const morgan = require('morgan')
const fs = require('fs')
const path = require('path')

const app = express()

// Development: Use 'dev' format for colored, concise output
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'))
}

// Production: Use 'combined' format and write to file
if (process.env.NODE_ENV === 'production') {
  const accessLogStream = fs.createWriteStream(
    path.join(__dirname, 'logs', 'access.log'),
    { flags: 'a' }
  )

  app.use(morgan('combined', { stream: accessLogStream }))
}

// Custom format example
morgan.token('host', (req) => req.hostname)
app.use(morgan(':method :url :status :response-time ms - :host'))

// Sample routes
app.get('/api/users', (req, res) => {
  res.json({ users: [] })
})

app.post('/api/users', (req, res) => {
  res.status(201).json({ message: 'User created' })
})

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

Here morgan(‘dev’) provides colored console output ideal for development with format: method url status response-time. The production configuration uses ‘combined’ format (Apache Combined Log Format) writing to access.log file via createWriteStream. Custom tokens extend Morgan’s functionality by adding application-specific data like hostname to log entries. The middleware placement before routes ensures all requests get logged automatically. Different environments use appropriate formats: dev for readability during development, combined for comprehensive production logging.

Best Practice Note:

This is the Morgan configuration we use in CoreUI Node.js backend services for reliable request logging across development and production environments. Skip logging for health check endpoints using morgan.skip option to reduce log noise, combine Morgan with Winston for comprehensive logging by writing Morgan output to Winston transports, and implement log rotation with rotating-file-stream to prevent disk space issues in production.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team