Morgan

HTTP request logger middleware for node.js

README

morgan

[![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url]

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](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):

  1. ```sh
  2. $ npm install morgan
  3. ```

API




  1. ``` js
  2. var morgan = require('morgan')
  3. ```

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




  1. ``` js
  2. morgan('tiny')
  3. ```

Using format string of predefined tokens




  1. ``` js
  2. morgan(':method :url :status :res[content-length] - :response-time ms')
  3. ```

Using a custom format function




  1. ``` js
  2. morgan(function (tokens, req, res) {
  3.   return [
  4.     tokens.method(req, res),
  5.     tokens.url(req, res),
  6.     tokens.status(req, res),
  7.     tokens.res(req, res, 'content-length'), '-',
  8.     tokens['response-time'](req, res), 'ms'
  9.   ].join(' ')
  10. })
  11. ```

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



  1. ``` js
  2. // EXAMPLE: only log error responses
  3. morgan('combined', {
  4.   skip: function (req, res) { return res.statusCode < 400 }
  5. })
  6. ```

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.

  1. ```
  2. :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
  3. ```

common

Standard Apache common log output.

  1. ```
  2. :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]
  3. ```

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.

  1. ```
  2. :method :url :status :response-time ms - :res[content-length]
  3. ```

short

Shorter than default, also including response time.

  1. ```
  2. :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
  3. ```

tiny

The minimal output.

  1. ```
  2. :method :url :status :res[content-length] - :response-time ms
  3. ```

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:



  1. ``` js
  2. morgan.token('type', function (req, res) { return req.headers['content-type'] })
  3. ```

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

  1. ``` js
  2. var express = require('express')
  3. var morgan = require('morgan')

  4. var app = express()

  5. app.use(morgan('combined'))

  6. app.get('/', function (req, res) {
  7.   res.send('hello, world!')
  8. })
  9. ```

vanilla http server


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

  1. ``` js
  2. var finalhandler = require('finalhandler')
  3. var http = require('http')
  4. var morgan = require('morgan')

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

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

  11.     // respond to request
  12.     res.setHeader('content-type', 'text/plain')
  13.     res.end('hello, world!')
  14.   })
  15. })
  16. ```

write logs to a file


single file


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

  1. ``` js
  2. var express = require('express')
  3. var fs = require('fs')
  4. var morgan = require('morgan')
  5. var path = require('path')

  6. var app = express()

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

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

  11. app.get('/', function (req, res) {
  12.   res.send('hello, world!')
  13. })
  14. ```

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

  1. ``` js
  2. var express = require('express')
  3. var morgan = require('morgan')
  4. var path = require('path')
  5. var rfs = require('rotating-file-stream') // version 2.x

  6. var app = express()

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

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

  14. app.get('/', function (req, res) {
  15.   res.send('hello, world!')
  16. })
  17. ```

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:

  1. ``` js
  2. var express = require('express')
  3. var fs = require('fs')
  4. var morgan = require('morgan')
  5. var path = require('path')

  6. var app = express()

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

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

  15. app.get('/', function (req, res) {
  16.   res.send('hello, world!')
  17. })
  18. ```

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.

  1. ``` js
  2. var express = require('express')
  3. var morgan = require('morgan')
  4. var uuid = require('node-uuid')

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

  8. var app = express()

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

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

  14. function assignId (req, res, next) {
  15.   req.id = uuid.v4()
  16.   next()
  17. }
  18. ```

License



[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/morgan/master
[coveralls-url]: https://coveralls.io/r/expressjs/morgan?branch=master
[npm-downloads-image]: https://badgen.net/npm/dm/morgan
[npm-url]: https://npmjs.org/package/morgan
[npm-version-image]: https://badgen.net/npm/v/morgan
[travis-image]: https://badgen.net/travis/expressjs/morgan/master
[travis-url]: https://travis-ci.org/expressjs/morgan