morgan vs express-winston vs bunyan vs morgan-body vs pino-http vs winston
HTTP Request Logging Middleware for Node.js Applications
morganexpress-winstonbunyanmorgan-bodypino-httpwinstonSimilar Packages:

HTTP Request Logging Middleware for Node.js Applications

bunyan, express-winston, morgan, morgan-body, pino-http, and winston are all npm packages used for logging HTTP requests in Node.js applications, but they differ significantly in architecture, performance, and integration style. morgan is a minimal, format-focused logger middleware originally built for Express. morgan-body extends morgan to include request and response bodies. bunyan and winston are general-purpose logging libraries that can be adapted to log HTTP traffic via middleware like express-winston (for Winston) or custom wrappers. pino-http is a high-performance HTTP logger built on the Pino logging framework, optimized for speed and structured JSON output.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
morgan10,058,6588,17430.6 kB369 months agoMIT
express-winston569,700797-555 years agoMIT
bunyan07,217-2945 years agoMIT
morgan-body010238.7 kB143 years agoMIT
pino-http069185.7 kB427 months agoMIT
winston024,424275 kB5204 months agoMIT

HTTP Request Logging in Node.js: bunyan, express-winston, morgan, morgan-body, pino-http, winston Compared

Choosing the right HTTP request logger impacts everything from debuggability to production performance and observability pipeline compatibility. These six packages represent different philosophies: minimal middleware (morgan), body-aware extensions (morgan-body), general-purpose loggers adapted for HTTP (bunyan, winston via express-winston), and purpose-built high-performance HTTP loggers (pino-http). Let’s compare them in real-world terms.

📝 Basic Setup: How Each Integrates with Express

All these packages work as Express middleware, but their setup complexity varies.

morgan is the simplest — just plug it in:

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

const app = express();
app.use(morgan('combined'));

morgan-body wraps morgan and requires body parsers to run first:

const express = require('express');
const bodyParser = require('body-parser');
const morganBody = require('morgan-body');

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
morganBody(app); // Note: mutates the app directly

express-winston needs an existing winston logger instance:

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

const app = express();
app.use(expressWinston.logger({
  transports: [new winston.transports.Console()],
  format: winston.format.combine(
    winston.format.colorize(),
    winston.format.json()
  )
}));

pino-http creates its own logger and attaches it to the request:

const express = require('express');
const pinoHttp = require('pino-http');

const app = express();
app.use(pinoHttp());

bunyan requires manual middleware wiring:

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

const log = bunyan.createLogger({ name: 'my-app' });
const app = express();

app.use((req, res, next) => {
  req.log = log.child({ reqId: Math.random().toString(36).substr(2, 9) });
  res.on('finish', () => {
    req.log.info({
      req: { method: req.method, url: req.url },
      res: { statusCode: res.statusCode }
    });
  });
  next();
});

winston alone doesn’t log HTTP requests — you must use express-winston or write custom middleware, so it’s not shown standalone here.

🗃️ Log Structure: Human-Readable vs Structured JSON

morgan defaults to Apache-style plain text:

127.0.0.1 - - [10/May/2024:14:23:01 +0000] "GET /api/users" 200 1234 "-" "curl/7.68.0"

You can customize formats, but it’s not JSON-native.

morgan-body extends this with bodies in development mode:

::ffff:127.0.0.1 - - [10/May/2024:14:25:01 +0000] "POST /login" 200 45 - 12.345 ms
REQ BODY: {"email":"test@example.com","password":"****"}
RES BODY: {"token":"abc123"}

pino-http, bunyan, and express-winston emit structured JSON by default:

{"level":30,"time":1715351101000,"pid":12345,"hostname":"host","req":{"id":1,"method":"GET","url":"/api/users","headers":{...}},"res":{"statusCode":200},"responseTime":12}

This makes them compatible with log aggregators like ELK, Datadog, or Loki without extra parsing.

⚡ Performance and Overhead

pino-http is built for speed — it avoids synchronous operations and uses asynchronous logging by default. Benchmarks consistently place it among the fastest HTTP loggers.

morgan is also lightweight because it does minimal work — no object serialization, just string formatting.

express-winston and bunyan are slower due to richer object manipulation and formatting layers. Winston’s transport system adds noticeable overhead under load.

morgan-body is the heaviest — it buffers entire request and response bodies in memory before logging, which can cause memory pressure and latency spikes with large payloads.

🔐 Sensitive Data Handling

Only morgan-body and express-winston provide built-in ways to redact fields:

// express-winston
app.use(expressWinston.logger({
  requestWhitelist: ['url', 'method'],
  bodyBlacklist: ['password', 'token']
}));

// morgan-body
morganBody(app, {
  logReqUserAgent: false,
  skip: (req, res) => req.path.startsWith('/health')
});
// But body redaction requires manual preprocessing

pino-http relies on Pino’s redaction feature:

app.use(pinoHttp({
  redact: ['req.body.password', 'res.body.token']
}));

morgan and raw bunyan offer no built-in redaction — you must sanitize data before it reaches the logger.

🔄 Request Context and Child Loggers

pino-http and bunyan support per-request child loggers, letting you attach context (like user ID or trace ID) that flows through all subsequent logs in that request:

// In pino-http route
app.get('/user/:id', (req, res) => {
  req.log.info(`Fetching user ${req.params.id}`);
  // This log includes the same reqId as the HTTP log
});

express-winston exposes req.winston but doesn’t automatically link child logs to the original request context without extra work.

morgan and morgan-body are fire-and-forget — they log the request at completion but don’t provide a logger instance for use in route handlers.

🛑 Deprecation and Maintenance Status

As of 2024:

  • bunyan is in maintenance mode. The author recommends Pino for new projects.
  • winston and express-winston are actively maintained but evolve slowly.
  • morgan is stable and widely used, though feature development has plateaued.
  • morgan-body hasn’t seen significant updates since 2020 and may have compatibility issues with newer Express versions.
  • pino-http is actively developed as part of the Pino ecosystem, with regular performance and feature updates.

🧪 Real-World Recommendations

For Production Microservices

Use pino-http. Its speed, structured output, and context propagation make it ideal for cloud-native apps feeding into centralized logging.

For Debugging APIs Locally

Use morgan-body temporarily. Disable it in production or guard it with environment checks:

if (process.env.NODE_ENV === 'development') {
  morganBody(app);
}

For Legacy Codebases Already Using Winston

Stick with express-winston to avoid rewriting logging infrastructure, but profile its impact under load.

For Simple Monitoring Needs

morgan with the 'combined' format is sufficient for basic access logs, especially when paired with infrastructure-level monitoring.

Avoid in New Projects

bunyan and morgan-body should generally be avoided for greenfield development due to maintenance status and performance characteristics, respectively.

📊 Summary Table

PackageFormatBody LoggingPer-Request ContextRedactionPerformanceMaintenance
morganPlain text⚡ HighStable
morgan-bodyPlain textManual🐢 LowDormant
express-winstonJSON✅ (opt-in)Partial🐢 MediumActive
bunyanJSONManualManual🐢 MediumMaintenance
pino-httpJSON✅ (opt-in)⚡⚡ Very HighActive
winstonJSONVia middlewareVia middleware🐢 MediumActive

💡 Final Thought

The best HTTP logger aligns with your observability strategy. If you’re shipping JSON logs to a modern backend, pino-http gives you the most value with the least overhead. If you just need quick visibility during development, morgan-body (used cautiously) gets the job done. Avoid over-engineering — sometimes morgan('dev') is all you really need.

How to Choose: morgan vs express-winston vs bunyan vs morgan-body vs pino-http vs winston

  • morgan:

    Choose morgan if you need a lightweight, battle-tested Express middleware that logs basic request info (method, URL, status, response time) with minimal setup. It’s ideal for development or simple production logging where human-readable formats like 'combined' or 'dev' suffice, but it doesn’t log request/response bodies or support structured JSON out of the box.

  • express-winston:

    Choose express-winston if you’re already using winston as your application logger and want a straightforward way to add Express request/response logging without switching ecosystems. It integrates cleanly with Winston transports and formats, but adds overhead due to Winston’s abstraction layer and isn’t optimized for high-throughput scenarios.

  • bunyan:

    Choose bunyan if you need a mature, structured JSON logger with strong CLI tooling (bunyan command for prettifying logs) and are comfortable writing your own Express middleware or using community adapters for HTTP logging. It’s well-suited for environments where log parsing and machine-readability are prioritized, but note that its development has slowed and it lacks some modern performance optimizations found in newer loggers.

  • morgan-body:

    Choose morgan-body if you require full visibility into request and response payloads alongside standard morgan-style logging, especially during debugging or API development. Be cautious in production — logging entire bodies can expose sensitive data and significantly increase I/O and memory usage. Always pair it with body sanitization and consider disabling it outside development.

  • pino-http:

    Choose pino-http if performance, structured JSON logging, and seamless integration with modern observability pipelines are critical. Built on Pino, it’s one of the fastest HTTP loggers available, automatically captures request IDs, and supports child loggers per request. It’s the best fit for high-scale services where log volume and ingestion efficiency matter.

  • winston:

    Choose winston if you need a highly configurable, transport-agnostic logging system that supports multiple output destinations (files, consoles, cloud services) and complex formatting rules. While powerful, its flexibility comes with performance costs, and for HTTP-specific logging, you’ll typically need express-winston or custom middleware — making it less optimal for pure request logging compared to purpose-built tools like pino-http.

README for morgan

morgan

NPM Version NPM Downloads Build Status Coverage Status

HTTP request logger middleware for node.js

Named after Dexter, a show you should not watch until completion.

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install morgan

API

var morgan = require('morgan')

morgan(format, options)

Create a new morgan logger middleware function using the given format and options. The format argument may be a string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry.

The format function will be called with three arguments tokens, req, and res, where tokens is an object with all defined tokens, req is the HTTP request and res is the HTTP response. The function is expected to return a string that will be the log line, or undefined / null to skip logging.

Using a predefined format string

morgan('tiny')

Using format string of predefined tokens

morgan(':method :url :status :res[content-length] - :response-time ms')

Using a custom format function

morgan(function (tokens, req, res) {
  return [
    tokens.method(req, res),
    tokens.url(req, res),
    tokens.status(req, res),
    tokens.res(req, res, 'content-length'), '-',
    tokens['response-time'](https://github.com/expressjs/morgan/blob/HEAD/req, res), 'ms'
  ].join(' ')
})

Options

Morgan accepts these properties in the options object.

immediate

Write log line on request instead of response. This means that a requests will be logged even if the server crashes, but data from the response (like the response code, content length, etc.) cannot be logged.

skip

Function to determine if logging is skipped, defaults to false. This function will be called as skip(req, res).

// EXAMPLE: only log error responses
morgan('combined', {
  skip: function (req, res) { return res.statusCode < 400 }
})
stream

Output stream for writing log lines, defaults to process.stdout.

Predefined Formats

There are various pre-defined formats provided:

combined

Standard Apache combined log output.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
# will output
::1 - - [27/Nov/2024:06:21:42 +0000] "GET /combined HTTP/1.1" 200 2 "-" "curl/8.7.1"
common

Standard Apache common log output.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]
# will output
::1 - - [27/Nov/2024:06:21:46 +0000] "GET /common HTTP/1.1" 200 2
dev

Concise output colored by response status for development use. The :status token will be colored green for success codes, red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for information codes.

:method :url :status :response-time ms - :res[content-length]
# will output
GET /dev 200 0.224 ms - 2
short

Shorter than default, also including response time.

:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
# will output
::1 - GET /short HTTP/1.1 200 2 - 0.283 ms
tiny

The minimal output.

:method :url :status :res[content-length] - :response-time ms
# will output
GET /tiny 200 2 - 0.188 ms

Tokens

Creating new tokens

To define a token, simply invoke morgan.token() with the name and a callback function. This callback function is expected to return a string value. The value returned is then available as ":type" in this case:

morgan.token('type', function (req, res) { return req.headers['content-type'] })

Calling morgan.token() using the same name as an existing token will overwrite that token definition.

The token function is expected to be called with the arguments req and res, representing the HTTP request and HTTP response. Additionally, the token can accept further arguments of it's choosing to customize behavior.

:date[format]

The current date and time in UTC. The available formats are:

  • clf for the common log format ("10/Oct/2000:13:55:36 +0000")
  • iso for the common ISO 8601 date time format (2000-10-10T13:55:36.000Z)
  • web for the common RFC 1123 date time format (Tue, 10 Oct 2000 13:55:36 GMT)

If no format is given, then the default is web.

:http-version

The HTTP version of the request.

:method

The HTTP method of the request.

:referrer

The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.

:remote-addr

The remote address of the request. This will use req.ip, otherwise the standard req.connection.remoteAddress value (socket address).

:remote-user

The user authenticated as part of Basic auth for the request.

:req[header]

The given header of the request. If the header is not present, the value will be displayed as "-" in the log.

:res[header]

The given header of the response. If the header is not present, the value will be displayed as "-" in the log.

:response-time[digits]

The time between the request coming into morgan and when the response headers are written, in milliseconds.

The digits argument is a number that specifies the number of digits to include on the number, defaulting to 3, which provides microsecond precision.

:status

The status code of the response.

If the request/response cycle completes before a response was sent to the client (for example, the TCP socket closed prematurely by a client aborting the request), then the status will be empty (displayed as "-" in the log).

:total-time[digits]

The time between the request coming into morgan and when the response has finished being written out to the connection, in milliseconds.

The digits argument is a number that specifies the number of digits to include on the number, defaulting to 3, which provides microsecond precision.

:url

The URL of the request. This will use req.originalUrl if exists, otherwise req.url.

:user-agent

The contents of the User-Agent header of the request.

morgan.compile(format)

Compile a format string into a format function for use by morgan. A format string is a string that represents a single log line and can utilize token syntax. Tokens are references by :token-name. If tokens accept arguments, they can be passed using [], for example: :token-name[pretty] would pass the string 'pretty' as an argument to the token token-name.

The function returned from morgan.compile takes three arguments tokens, req, and res, where tokens is object with all defined tokens, req is the HTTP request and res is the HTTP response. The function will return a string that will be the log line, or undefined / null to skip logging.

Normally formats are defined using morgan.format(name, format), but for certain advanced uses, this compile function is directly available.

Examples

express/connect

Sample app that will log all request in the Apache combined format to STDOUT

var express = require('express')
var morgan = require('morgan')

var app = express()

app.use(morgan('combined'))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

vanilla http server

Sample app that will log all request in the Apache combined format to STDOUT

var finalhandler = require('finalhandler')
var http = require('http')
var morgan = require('morgan')

// create "middleware"
var logger = morgan('combined')

http.createServer(function (req, res) {
  var done = finalhandler(req, res)
  logger(req, res, function (err) {
    if (err) return done(err)

    // respond to request
    res.setHeader('content-type', 'text/plain')
    res.end('hello, world!')
  })
})

write logs to a file

single file

Sample app that will log all requests in the Apache combined format to the file access.log.

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

var app = express()

// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })

// setup the logger
app.use(morgan('combined', { stream: accessLogStream }))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

log file rotation

Sample app that will log all requests in the Apache combined format to one log file per day in the log/ directory using the rotating-file-stream module.

var express = require('express')
var morgan = require('morgan')
var path = require('path')
var rfs = require('rotating-file-stream') // version 2.x

var app = express()

// create a rotating write stream
var accessLogStream = rfs.createStream('access.log', {
  interval: '1d', // rotate daily
  path: path.join(__dirname, 'log')
})

// setup the logger
app.use(morgan('combined', { stream: accessLogStream }))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

split / dual logging

The morgan middleware can be used as many times as needed, enabling combinations like:

  • Log entry on request and one on response
  • Log all requests to file, but errors to console
  • ... and more!

Sample app that will log all requests to a file using Apache format, but error responses are logged to the console:

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

var app = express()

// log only 4xx and 5xx responses to console
app.use(morgan('dev', {
  skip: function (req, res) { return res.statusCode < 400 }
}))

// log all requests to access.log
app.use(morgan('common', {
  stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
}))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

use custom token formats

Sample app that will use custom token formats. This adds an ID to all requests and displays it using the :id token.

var express = require('express')
var morgan = require('morgan')
var uuid = require('node-uuid')

morgan.token('id', function getId (req) {
  return req.id
})

var app = express()

app.use(assignId)
app.use(morgan(':id :method :url :response-time'))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

function assignId (req, res, next) {
  req.id = uuid.v4()
  next()
}

License

MIT