3 [![NPM Version][npm-image]][npm-url]
4 [![NPM Downloads][downloads-image]][downloads-url]
5 [![Build Status][travis-image]][travis-url]
6 [![Test Coverage][coveralls-image]][coveralls-url]
8 HTTP request logger middleware for node.js
10 > Named after [Dexter](http://en.wikipedia.org/wiki/Dexter_Morgan), a show you should not watch until completion.
14 <!-- eslint-disable no-unused-vars -->
17 var morgan = require('morgan')
20 ### morgan(format, options)
22 Create a new morgan logger middleware function using the given `format` and `options`.
23 The `format` argument may be a string of a predefined name (see below for the names),
24 a string of a format string, or a function that will produce a log entry.
26 The `format` function will be called with three arguments `tokens`, `req`, and `res`,
27 where `tokens` is an object with all defined tokens, `req` is the HTTP request and `res`
28 is the HTTP response. The function is expected to return a string that will be the log
29 line, or `undefined` / `null` to skip logging.
31 #### Using a predefined format string
33 <!-- eslint-disable no-undef -->
39 #### Using format string of predefined tokens
41 <!-- eslint-disable no-undef -->
44 morgan(':method :url :status :res[content-length] - :response-time ms')
47 #### Using a custom format function
49 <!-- eslint-disable no-undef -->
52 morgan(function (tokens, req, res) {
54 tokens.method(req, res),
56 tokens.status(req, res),
57 tokens.res(req, res, 'content-length'), '-',
58 tokens['response-time'](req, res), 'ms'
65 Morgan accepts these properties in the options object.
69 Write log line on request instead of response. This means that a requests will
70 be logged even if the server crashes, _but data from the response (like the
71 response code, content length, etc.) cannot be logged_.
75 Function to determine if logging is skipped, defaults to `false`. This function
76 will be called as `skip(req, res)`.
78 <!-- eslint-disable no-undef -->
81 // EXAMPLE: only log error responses
83 skip: function (req, res) { return res.statusCode < 400 }
89 Output stream for writing log lines, defaults to `process.stdout`.
91 #### Predefined Formats
93 There are various pre-defined formats provided:
97 Standard Apache combined log output.
100 :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
105 Standard Apache common log output.
108 :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]
113 Concise output colored by response status for development use. The `:status`
114 token will be colored red for server error codes, yellow for client error
115 codes, cyan for redirection codes, and uncolored for all other codes.
118 :method :url :status :response-time ms - :res[content-length]
123 Shorter than default, also including response time.
126 :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
134 :method :url :status :res[content-length] - :response-time ms
139 ##### Creating new tokens
141 To define a token, simply invoke `morgan.token()` with the name and a callback function.
142 This callback function is expected to return a string value. The value returned is then
143 available as ":type" in this case:
145 <!-- eslint-disable no-undef -->
148 morgan.token('type', function (req, res) { return req.headers['content-type'] })
151 Calling `morgan.token()` using the same name as an existing token will overwrite that
154 The token function is expected to be called with the arguments `req` and `res`, representing
155 the HTTP request and HTTP response. Additionally, the token can accept further arguments of
156 it's choosing to customize behavior.
160 The current date and time in UTC. The available formats are:
162 - `clf` for the common log format (`"10/Oct/2000:13:55:36 +0000"`)
163 - `iso` for the common ISO 8601 date time format (`2000-10-10T13:55:36.000Z`)
164 - `web` for the common RFC 1123 date time format (`Tue, 10 Oct 2000 13:55:36 GMT`)
166 If no format is given, then the default is `web`.
170 The HTTP version of the request.
174 The HTTP method of the request.
178 The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.
182 The remote address of the request. This will use `req.ip`, otherwise the standard `req.connection.remoteAddress` value (socket address).
186 The user authenticated as part of Basic auth for the request.
190 The given `header` of the request. If the header is not present, the
191 value will be displayed as `"-"` in the log.
195 The given `header` of the response. If the header is not present, the
196 value will be displayed as `"-"` in the log.
198 ##### :response-time[digits]
200 The time between the request coming into `morgan` and when the response
201 headers are written, in milliseconds.
203 The `digits` argument is a number that specifies the number of digits to
204 include on the number, defaulting to `3`, which provides microsecond precision.
208 The status code of the response.
210 If the request/response cycle completes before a response was sent to the
211 client (for example, the TCP socket closed prematurely by a client aborting
212 the request), then the status will be empty (displayed as `"-"` in the log).
216 The URL of the request. This will use `req.originalUrl` if exists, otherwise `req.url`.
220 The contents of the User-Agent header of the request.
222 ### morgan.compile(format)
224 Compile a format string into a `format` function for use by `morgan`. A format string
225 is a string that represents a single log line and can utilize token syntax.
226 Tokens are references by `:token-name`. If tokens accept arguments, they can
227 be passed using `[]`, for example: `:token-name[pretty]` would pass the string
228 `'pretty'` as an argument to the token `token-name`.
230 The function returned from `morgan.compile` takes three arguments `tokens`, `req`, and
231 `res`, where `tokens` is object with all defined tokens, `req` is the HTTP request and
232 `res` is the HTTP response. The function will return a string that will be the log line,
233 or `undefined` / `null` to skip logging.
235 Normally formats are defined using `morgan.format(name, format)`, but for certain
236 advanced uses, this compile function is directly available.
242 Simple app that will log all request in the Apache combined format to STDOUT
245 var express = require('express')
246 var morgan = require('morgan')
250 app.use(morgan('combined'))
252 app.get('/', function (req, res) {
253 res.send('hello, world!')
257 ### vanilla http server
259 Simple app that will log all request in the Apache combined format to STDOUT
262 var finalhandler = require('finalhandler')
263 var http = require('http')
264 var morgan = require('morgan')
266 // create "middleware"
267 var logger = morgan('combined')
269 http.createServer(function (req, res) {
270 var done = finalhandler(req, res)
271 logger(req, res, function (err) {
272 if (err) return done(err)
274 // respond to request
275 res.setHeader('content-type', 'text/plain')
276 res.end('hello, world!')
281 ### write logs to a file
285 Simple app that will log all requests in the Apache combined format to the file
289 var express = require('express')
290 var fs = require('fs')
291 var morgan = require('morgan')
292 var path = require('path')
296 // create a write stream (in append mode)
297 var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
300 app.use(morgan('combined', { stream: accessLogStream }))
302 app.get('/', function (req, res) {
303 res.send('hello, world!')
307 #### log file rotation
309 Simple app that will log all requests in the Apache combined format to one log
310 file per day in the `log/` directory using the
311 [rotating-file-stream module](https://www.npmjs.com/package/rotating-file-stream).
314 var express = require('express')
315 var fs = require('fs')
316 var morgan = require('morgan')
317 var path = require('path')
318 var rfs = require('rotating-file-stream')
321 var logDirectory = path.join(__dirname, 'log')
323 // ensure log directory exists
324 fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
326 // create a rotating write stream
327 var accessLogStream = rfs('access.log', {
328 interval: '1d', // rotate daily
333 app.use(morgan('combined', { stream: accessLogStream }))
335 app.get('/', function (req, res) {
336 res.send('hello, world!')
340 ### split / dual logging
342 The `morgan` middleware can be used as many times as needed, enabling
345 * Log entry on request and one on response
346 * Log all requests to file, but errors to console
349 Sample app that will log all requests to a file using Apache format, but
350 error responses are logged to the console:
353 var express = require('express')
354 var fs = require('fs')
355 var morgan = require('morgan')
356 var path = require('path')
360 // log only 4xx and 5xx responses to console
361 app.use(morgan('dev', {
362 skip: function (req, res) { return res.statusCode < 400 }
365 // log all requests to access.log
366 app.use(morgan('common', {
367 stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
370 app.get('/', function (req, res) {
371 res.send('hello, world!')
375 ### use custom token formats
377 Sample app that will use custom token formats. This adds an ID to all requests and displays it using the `:id` token.
380 var express = require('express')
381 var morgan = require('morgan')
382 var uuid = require('node-uuid')
384 morgan.token('id', function getId (req) {
391 app.use(morgan(':id :method :url :response-time'))
393 app.get('/', function (req, res) {
394 res.send('hello, world!')
397 function assignId (req, res, next) {
407 [npm-image]: https://img.shields.io/npm/v/morgan.svg
408 [npm-url]: https://npmjs.org/package/morgan
409 [travis-image]: https://img.shields.io/travis/expressjs/morgan/master.svg
410 [travis-url]: https://travis-ci.org/expressjs/morgan
411 [coveralls-image]: https://img.shields.io/coveralls/expressjs/morgan/master.svg
412 [coveralls-url]: https://coveralls.io/r/expressjs/morgan?branch=master
413 [downloads-image]: https://img.shields.io/npm/dm/morgan.svg
414 [downloads-url]: https://npmjs.org/package/morgan