morgan, morgan-body, and winston are all logging tools used in Node.js applications, but they serve different scopes and purposes. morgan is a middleware specifically designed for HTTP request logging in Express.js applications, providing concise, standardized output of incoming requests. morgan-body extends this concept by automatically logging both request and response bodies alongside standard HTTP metadata, making it useful for debugging APIs during development. winston, in contrast, is a general-purpose, transport-agnostic logging library that supports structured logging, multiple output destinations (like files, consoles, or external services), and log levels—making it suitable for comprehensive application-wide logging beyond just HTTP traffic.
When building Node.js applications — especially those using Express — developers often face a choice between specialized HTTP logging and general-purpose application logging. morgan, morgan-body, and winston each address different needs in the observability stack. Let’s break down how they work, where they overlap, and when to use which.
morgan focuses exclusively on HTTP request metadata. It logs one line per request with details like method, URL, status code, response time, and content length — but never the request or response body.
// morgan: Basic HTTP logging
import morgan from 'morgan';
import express from 'express';
const app = express();
app.use(morgan('combined')); // Standard Apache combined log format
morgan-body builds on morgan's foundation but automatically logs full request and response bodies (when they’re JSON or form-encoded). This makes it a developer-friendly tool for API debugging.
// morgan-body: Logs bodies + metadata
import morganBody from 'morgan-body';
import express from 'express';
const app = express();
morganBody(app); // Attaches middleware that logs req/res bodies
winston is a general-purpose logger that doesn’t know anything about HTTP by default. You can log anything — errors, user actions, cron jobs — and send logs to multiple destinations. To log HTTP requests, you must write custom middleware.
// winston: Manual HTTP logging via custom middleware
import winston from 'winston';
import express from 'express';
const logger = winston.createLogger({
level: 'info',
transports: [new winston.transports.Console()]
});
const app = express();
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
logger.info(`${req.method} ${req.url} ${res.statusCode} ${Date.now() - start}ms`);
});
next();
});
morgan offers predefined formats (tiny, dev, combined) and a token system to customize output. You can define your own tokens to include things like user IDs from sessions.
// morgan: Custom token example
morgan.token('user', (req) => req.user?.id || '-');
app.use(morgan(':method :url :status :user')); // e.g., "GET /api/data 200 123"
morgan-body provides zero-configuration body logging out of the box. It parses JSON and URL-encoded bodies automatically and includes them in colored console output. However, it offers limited customization compared to morgan.
// morgan-body: No config needed for body logging
// Automatically logs:
// → POST /login {"email":"test@example.com"}
// ← 200 {"token":"..."}
winston gives you full control over structure, level, and destination. You can add metadata, use JSON formatting, and route logs to files, databases, or services like Datadog. But you must implement HTTP logging yourself.
// winston: Structured logging with metadata
logger.info('User login attempt', {
email: 'test@example.com',
ip: '192.168.1.1',
userAgent: 'Mozilla/5.0...'
});
morgan is optimized for production. It’s minimal, fast, and widely used in high-traffic apps. Since it avoids logging large payloads, it won’t slow down your server or expose sensitive data.
morgan-body is not recommended for production. Logging full request/response bodies can:
winston is production-ready when configured properly. You can disable verbose logging in production, filter sensitive fields, and use asynchronous transports to avoid blocking the event loop.
// winston: Safe production setup
const logger = winston.createLogger({
level: process.env.NODE_ENV === 'production' ? 'warn' : 'debug',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.Console({
format: winston.format.simple()
})
]
});
All three integrate with Express, but differently:
morgan: Drop-in middleware. Works instantly with any Express app.morgan-body: Also drop-in, but must be added after body-parsing middleware (like express.json()) to access parsed bodies.winston: Requires manual middleware to capture HTTP details. You lose convenience but gain precision.// Correct order for morgan-body
app.use(express.json()); // Parse JSON first
morganBody(app); // Then log bodies
// winston requires explicit timing and status capture
app.use((req, res, next) => {
req.startAt = process.hrtime();
const originalSend = res.send;
res.send = function (body) {
// Log here if needed
return originalSend.call(this, body);
};
next();
});
Yes — and often should. A common pattern in production apps is:
morgan for lightweight HTTP access logswinston for application-level events (errors, business logic)morgan-body in production entirely// Combined approach
import morgan from 'morgan';
import winston from 'winston';
const app = express();
// HTTP access logging
app.use(morgan('combined'));
// Application logging
const logger = winston.createLogger({ /* ... */ });
app.post('/checkout', (req, res) => {
try {
processPayment(req.body);
logger.info('Payment processed', { userId: req.user.id });
res.status(200).json({ success: true });
} catch (err) {
logger.error('Payment failed', { error: err.message, userId: req.user.id });
res.status(500).json({ error: 'Failed' });
}
});
| Concern | morgan | morgan-body | winston |
|---|---|---|---|
| Primary Use Case | HTTP access logs | Debugging API payloads | Full application logging |
| Logs Request/Response Bodies? | ❌ No | ✅ Yes | ❌ Only if manually implemented |
| Production Safe? | ✅ Yes | ❌ No | ✅ Yes (with proper config) |
| Custom Formatting | ✅ Token-based | ❌ Limited | ✅ Fully customizable |
| Multiple Destinations | ❌ Console only (unless wrapped) | ❌ Console only | ✅ Files, console, cloud, etc. |
| Log Levels | ❌ All logs same level | ❌ All logs same level | ✅ info, warn, error, debug, etc. |
morgan. It’s fast, secure, and does exactly what it says.morgan-body to quickly see what’s being sent and received — but never deploy it to production.winston as your application’s central logger, and optionally pair it with morgan for access logs.Remember: logging bodies in production is almost always a bad idea unless you’ve carefully filtered sensitive fields. Tools like morgan-body are great for development speed, but winston and morgan give you the control and safety needed for real-world systems.
Choose morgan when you need a lightweight, battle-tested Express middleware for logging basic HTTP request details like method, URL, status code, and response time. It’s ideal for production environments where performance and minimal overhead matter, and you don’t need to inspect request or response payloads. Its token-based format system offers flexibility without complexity.
Choose morgan-body during development or in non-production environments where you need to see full request and response bodies alongside standard HTTP logs for debugging REST APIs. It’s especially helpful when working with JSON APIs and troubleshooting payload issues, but avoid it in production due to potential performance impact and security risks from logging sensitive data.
Choose winston when you need a robust, flexible logging system that goes beyond HTTP requests—supporting structured logs, multiple transports (console, file, cloud services), log levels, and metadata. It’s well-suited for production applications requiring audit trails, error tracking, or integration with monitoring systems, though it doesn’t provide built-in HTTP middleware like morgan.
HTTP request logger middleware for node.js
Named after Dexter, a show you should not watch until completion.
This is a Node.js module available through the
npm registry. Installation is done using the
npm install command:
$ npm install morgan
var morgan = require('morgan')
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.
morgan('tiny')
morgan(':method :url :status :res[content-length] - :response-time ms')
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'](req, res), 'ms'
].join(' ')
})
Morgan accepts these properties in the options object.
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.
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 }
})
Output stream for writing log lines, defaults to process.stdout.
There are various pre-defined formats provided:
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"
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
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
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
The minimal output.
:method :url :status :res[content-length] - :response-time ms
# will output
GET /tiny 200 2 - 0.188 ms
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.
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.
The HTTP version of the request.
The HTTP method of the request.
The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.
The remote address of the request. This will use req.ip, otherwise the standard req.connection.remoteAddress value (socket address).
The user authenticated as part of Basic auth for the request.
The given header of the request. If the header is not present, the
value will be displayed as "-" in the log.
The given header of the response. If the header is not present, the
value will be displayed as "-" in the log.
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.
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).
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.
The URL of the request. This will use req.originalUrl if exists, otherwise req.url.
The contents of the User-Agent header of the request.
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.
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!')
})
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!')
})
})
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!')
})
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!')
})
The morgan middleware can be used as many times as needed, enabling
combinations like:
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!')
})
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()
}