winston, bunyan, and log4js are general-purpose logging libraries designed to capture application events, errors, and debug information across any part of a Node.js system. morgan is different — it is specialized HTTP request logger middleware built specifically for web frameworks like Express. While the general loggers handle broad application state, morgan focuses strictly on incoming web traffic, such as response times and status codes. Teams often use morgan alongside winston to get full visibility into both request flow and internal logic.
Choosing the right logging tool depends on whether you need to track general application events or specific web traffic. winston, bunyan, and log4js are general-purpose loggers, while morgan is HTTP middleware. Understanding this split is critical for building observable systems.
winston is designed for general application logging.
// winston: General application logging
const winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'app.log' })
]
});
logger.info('User logged in', { userId: 123 });
bunyan focuses on structured JSON logging for services.
// bunyan: Structured JSON logging
const bunyan = require('bunyan');
const logger = bunyan.createLogger({ name: 'my-service' });
logger.info({ userId: 123 }, 'User logged in');
log4js brings Java-style logging categories to Node.js.
// log4js: Category-based logging
const log4js = require('log4js');
log4js.configure({ appenders: { out: { type: 'stdout' } }, categories: { default: { appenders: ['out'], level: 'info' } } });
const logger = log4js.getLogger();
logger.info('User logged in');
morgan is strictly for HTTP request logging.
// morgan: HTTP request logging
const morgan = require('morgan');
const express = require('express');
const app = express();
app.use(morgan('combined'));
// Logs: GET /api/users 200 15ms
How you send logs to different places varies widely between these tools.
winston uses a transport system that is easy to extend.
// winston: Multiple transports
const logger = winston.createLogger({
transports: [
new winston.transports.Console(),
new winston.transports.HTTP({ url: 'http://log-server.com' })
]
});
bunyan uses streams to define outputs.
// bunyan: Streams configuration
const logger = bunyan.createLogger({
name: 'my-app',
streams: [
{ level: 'info', stream: process.stdout },
{ level: 'error', path: '/var/log/my-app-error.log' }
]
});
log4js uses appenders configured in a central object.
// log4js: Appenders configuration
log4js.configure({
appenders: {
file: { type: 'file', filename: 'app.log' },
console: { type: 'stdout' }
},
categories: {
default: { appenders: ['file', 'console'], level: 'info' }
}
});
morgan does not support multiple transports natively.
// morgan: Custom stream for transport
const writeStream = fs.createWriteStream('access.log', { flags: 'a' });
app.use(morgan('combined', { stream: writeStream }));
The shape of your log data affects how easily you can search it later.
winston lets you choose between text and JSON.
winston.format.simple() for readability.winston.format.json() for machine parsing.// winston: Custom format
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [new winston.transports.Console()]
});
bunyan outputs JSON by default.
// bunyan: Default JSON output
// Terminal output: {"name":"my-service","hostname":"local","pid":123,"level":30,"msg":"User logged in","time":"..."}
log4js supports patterns similar to Log4j.
%d{yyyy-MM-dd} %p %m.// log4js: Pattern layout
log4js.configure({
appenders: {
out: { type: 'stdout', layout: { type: 'pattern', pattern: '%d %p %m' } }
},
categories: { default: { appenders: ['out'], level: 'info' } }
});
morgan uses predefined tokens for HTTP data.
:method :url :status :res[content-length].// morgan: Custom format tokens
app.use(morgan(':method :url :status :response-time ms'));
Long-term support matters when picking a core dependency.
winston is highly active and widely adopted.
bunyan has low maintenance activity recently.
log4js is actively maintained with regular updates.
morgan is the standard for Express logging.
| Feature | winston | bunyan | log4js | morgan |
|---|---|---|---|---|
| Type | General Logger | General Logger | General Logger | HTTP Middleware |
| Default Format | Text or JSON | JSON Only | Text Pattern | Text Tokens |
| Transports | Built-in System | Streams | Appenders | Single Stream |
| Best For | Modern Node Apps | JSON Pipelines | Java-style Logs | Express Requests |
| Maintenance | High | Low | Medium | High |
winston is the versatile workhorse 🐴 — pick it for most general logging needs in modern Node.js apps. It balances ease of use with powerful features.
morgan is the traffic cop 👮 — use it specifically for logging web requests in Express. It works best when paired with a general logger like winston.
bunyan is the legacy specialist 📜 — only use it if you are maintaining older systems that rely on its strict JSON streams. New projects should look elsewhere.
log4js is the enterprise choice 🏢 — ideal if your team needs complex categories or comes from a Java background.
Final Thought: For a typical web API, combine morgan for request logs and winston for application logic. This gives you full visibility without overcomplicating your stack.
Choose morgan when you need to log HTTP requests in an Express or Connect application. It is not a general logger, so pair it with winston or bunyan for application errors. It is the standard choice for tracking API usage, response times, and status codes with minimal setup.
Choose log4js if your team comes from a Java background and prefers Log4j-style configuration patterns. It supports complex appenders and categories out of the box. It is a solid choice for enterprise applications that require strict logging hierarchies and file rotation without custom code.
Choose bunyan only if you are maintaining a legacy system that already depends on it. Development activity has slowed significantly, and it lacks modern features found in newer libraries. For new projects, prefer winston or pino to ensure better long-term support and performance.
Choose winston for most new Node.js projects because it offers the best balance of flexibility and community support. It supports multiple transports (like files and consoles) and custom formats without heavy configuration. It is the safest bet for long-term maintenance and integrates well with cloud monitoring tools.
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
For ES Modules:
import morgan from 'morgan'
For CommonJS:
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'](https://github.com/expressjs/morgan/blob/HEAD/req, res), 'ms'
].join(' ')
})
Morgan accepts these properties in the options object.
Write log line on request instead of response. This means that 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.
If the stream is in object mode (stream.writableObjectMode is true) and the
format function returns an object, the object is written to the stream as-is,
without a trailing newline. This allows passing structured log entries to
loggers that accept objects:
morgan(function (tokens, req, res) {
return {
method: tokens.method(req, res),
url: tokens.url(req, res),
status: Number(tokens.status(req, res))
}
}, {
stream: {
writableObjectMode: true,
write: function (entry) {
// entry is the object returned by the format function
}
}
})
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
Coloring is disabled when the NO_COLOR environment
variable is set to any non-empty value, in which case the output above is
written without any escape sequences. The variable is read once, when morgan
is first required.
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
its 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 process ID of the Node.js process handling the request.
The Referrer header of the request. This will use the standard mis-spelled Referer header if it 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 it 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 referenced 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 an 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 requests 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 requests 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('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()
}