Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

morgan

expressjs23.2mMIT1.10.0TypeScript support: definitely-typed

HTTP request logger middleware for node.js

express, http, logger, middleware

readme

morgan

NPM Version NPM Downloads Build Status Test Coverage

HTTP request logger middleware for node.js

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

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'](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"
common

Standard Apache common log output.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]
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]
short

Shorter than default, also including response time.

:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
tiny

The minimal output.

:method :url :status :res[content-length] - :response-time 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

Simple 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

Simple 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

Simple 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

Simple 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

changelog

1.10.0 / 2020-03-20

  • Add :total-time token
  • Fix trailing space in colored status code for dev format
  • deps: basic-auth@~2.0.1
  • deps: depd@~2.0.0
    • Replace internal eval usage with Function constructor
    • Use instance methods on process to check for listeners
  • deps: on-headers@~1.0.2
    • Fix res.writeHead patch missing return value

1.9.1 / 2018-09-10

  • Fix using special characters in format
  • deps: depd@~1.1.2
    • perf: remove argument reassignment

1.9.0 / 2017-09-26

  • Use res.headersSent when available
  • deps: basic-auth@~2.0.0
    • Use safe-buffer for improved Buffer API
  • deps: debug@2.6.9
  • deps: depd@~1.1.1
    • Remove unnecessary Buffer loading

1.8.2 / 2017-05-23

1.8.1 / 2017-02-04

  • deps: debug@2.6.1
    • Fix deprecation messages in WebStorm and other editors
    • Undeprecate DEBUG_FD set to 1 or 2

1.8.0 / 2017-02-04

  • Fix sending unnecessary undefined argument to token functions
  • deps: basic-auth@~1.1.0
  • deps: debug@2.6.0
    • Allow colors in workers
    • Deprecated DEBUG_FD environment variable
    • Fix error when running under React Native
    • Use same color for same namespace
    • deps: ms@0.7.2
  • perf: enable strict mode in compiled functions

1.7.0 / 2016-02-18

  • Add digits argument to response-time token
  • deps: depd@~1.1.0
    • Enable strict mode in more places
    • Support web browser loading
  • deps: on-headers@~1.0.1
    • perf: enable strict mode

1.6.1 / 2015-07-03

  • deps: basic-auth@~1.0.3

1.6.0 / 2015-06-12

  • Add morgan.compile(format) export
  • Do not color 1xx status codes in dev format
  • Fix response-time token to not include response latency
  • Fix status token incorrectly displaying before response in dev format
  • Fix token return values to be undefined or a string
  • Improve representation of multiple headers in req and res tokens
  • Use res.getHeader in res token
  • deps: basic-auth@~1.0.2
    • perf: enable strict mode
    • perf: hoist regular expression
    • perf: parse with regular expressions
    • perf: remove argument reassignment
  • deps: on-finished@~2.3.0
    • Add defined behavior for HTTP CONNECT requests
    • Add defined behavior for HTTP Upgrade requests
    • deps: ee-first@1.1.1
  • pref: enable strict mode
  • pref: reduce function closure scopes
  • pref: remove dynamic compile on every request for dev format
  • pref: remove an argument reassignment
  • pref: skip function call without skip option

1.5.3 / 2015-05-10

  • deps: basic-auth@~1.0.1
  • deps: debug@~2.2.0
  • deps: depd@~1.0.1
  • deps: on-finished@~2.2.1
    • Fix isFinished(req) when data buffered

1.5.2 / 2015-03-15

  • deps: debug@~2.1.3
    • Fix high intensity foreground color for bold
    • deps: ms@0.7.0

1.5.1 / 2014-12-31

  • deps: debug@~2.1.1
  • deps: on-finished@~2.2.0

1.5.0 / 2014-11-06

  • Add multiple date formats
    • clf for the common log format
    • iso for the common ISO 8601 date time format
    • web for the common RFC 1123 date time format
  • Deprecate buffer option
  • Fix date format in common and combined formats
  • Fix token arguments to accept values with "

1.4.1 / 2014-10-22

  • deps: on-finished@~2.1.1
    • Fix handling of pipelined requests

1.4.0 / 2014-10-16

  • Add debug messages
  • deps: depd@~1.0.0

1.3.2 / 2014-09-27

  • Fix req.ip integration when immediate: false

1.3.1 / 2014-09-14

  • Remove un-used bytes dependency
  • deps: depd@0.4.5

1.3.0 / 2014-09-01

  • Assert if format is not a function or string

1.2.3 / 2014-08-16

1.2.2 / 2014-07-27

  • deps: depd@0.4.4
    • Work-around v8 generating empty stack traces

1.2.1 / 2014-07-26

  • deps: depd@0.4.3
    • Fix exception when global Error.stackTraceLimit is too low

1.2.0 / 2014-07-19

  • Add :remote-user token
  • Add combined log format
  • Add common log format
  • Add morgan(format, options) function signature
  • Deprecate default format -- use combined format instead
  • Deprecate not providing a format
  • Remove non-standard grey color from dev format

1.1.1 / 2014-05-20

  • simplify method to get remote address

1.1.0 / 2014-05-18

  • "dev" format will use same tokens as other formats
  • :response-time token is now empty when immediate used
  • :response-time token is now monotonic
  • :response-time token has precision to 1 μs
  • fix :status + immediate output in node.js 0.8
  • improve buffer option to prevent indefinite event loop holding
  • deps: bytes@1.0.0
    • add negative support

1.0.1 / 2014-05-04

  • Make buffer unique per morgan instance
  • deps: bytes@0.3.0
    • added terabyte support

1.0.0 / 2014-02-08

  • Initial release