morgan vs log4js vs bunyan vs winston
Node.js Logging Architecture: General Loggers vs HTTP Middleware
morganlog4jsbunyanwinstonSimilar Packages:

Node.js Logging Architecture: General Loggers vs HTTP Middleware

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.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
morgan17,596,8528,20227.8 kB252 months agoMIT
log4js9,161,0705,824160 kB994 years agoApache-2.0
bunyan07,208-2906 years agoMIT
winston024,527275 kB545a year agoMIT

Node.js Logging Architecture: General Loggers vs HTTP Middleware

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.

🎯 Core Purpose: General Events vs HTTP Requests

winston is designed for general application logging.

  • It handles errors, info messages, and debug data from any part of your code.
  • You can send logs to files, consoles, or external services simultaneously.
// 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.

  • It forces logs into JSON format by default, which helps with parsing.
  • Best for systems where logs are shipped to a centralized JSON analyzer.
// 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.

  • It allows you to define different rules for different parts of the app.
  • Useful for large apps where database logs need different handling than UI logs.
// 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.

  • It sits in your web server middleware stack.
  • It logs method, URL, status, and response time for every web request.
// 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

⚙️ Configuration & Transports

How you send logs to different places varies widely between these tools.

winston uses a transport system that is easy to extend.

  • You can add multiple outputs in the config array.
  • Great for sending logs to both a file and a service like Splunk.
// 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.

  • You define a stream array with level and type.
  • Less flexible than Winston but very clear for JSON pipelines.
// 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.

  • You map categories to specific appenders.
  • Powerful for routing logs based on source.
// 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.

  • It writes to a stream you provide.
  • To send elsewhere, you must pipe its stream to a writer.
// morgan: Custom stream for transport
const writeStream = fs.createWriteStream('access.log', { flags: 'a' });
app.use(morgan('combined', { stream: writeStream }));

📝 Log Format & Structure

The shape of your log data affects how easily you can search it later.

winston lets you choose between text and JSON.

  • You can use winston.format.simple() for readability.
  • Or 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.

  • Every log line is a valid JSON object.
  • Requires a CLI tool to read nicely in the terminal.
// 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.

  • You can define layouts like %d{yyyy-MM-dd} %p %m.
  • Good for teams who want traditional text logs.
// 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.

  • Formats like :method :url :status :res[content-length].
  • You can create custom tokens if needed.
// morgan: Custom format tokens
app.use(morgan(':method :url :status :response-time ms'));

🛠️ Maintenance & Ecosystem

Long-term support matters when picking a core dependency.

winston is highly active and widely adopted.

  • It has a large plugin ecosystem for transports.
  • Safe choice for new projects requiring stability.

bunyan has low maintenance activity recently.

  • It is stable but not evolving with new Node.js features.
  • Avoid for new projects unless you need its specific JSON stream style.

log4js is actively maintained with regular updates.

  • It remains a strong choice for enterprise patterns.
  • Good documentation and stable API.

morgan is the standard for Express logging.

  • It is lightweight and rarely changes because HTTP standards are stable.
  • Essential for any Express-based API.

📊 Summary: Key Differences

Featurewinstonbunyanlog4jsmorgan
TypeGeneral LoggerGeneral LoggerGeneral LoggerHTTP Middleware
Default FormatText or JSONJSON OnlyText PatternText Tokens
TransportsBuilt-in SystemStreamsAppendersSingle Stream
Best ForModern Node AppsJSON PipelinesJava-style LogsExpress Requests
MaintenanceHighLowMediumHigh

💡 The Big Picture

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.

How to Choose: morgan vs log4js vs bunyan vs winston

  • morgan:

    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.

  • log4js:

    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.

  • bunyan:

    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.

  • winston:

    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.

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

For ES Modules:

import morgan from 'morgan'

For CommonJS:

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 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.

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
    }
  }
})

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

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.

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 its 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.

:pid

The process ID of the Node.js process handling the request.

:referrer

The Referrer header of the request. This will use the standard mis-spelled Referer header if it 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 it 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 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.

Examples

express/connect

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!')
})

vanilla http server

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!')
  })
})

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('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