UNPKG

10.9 kBMarkdownView Raw
1# morgan
2
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]
7
8HTTP request logger middleware for node.js
9
10> Named after [Dexter](http://en.wikipedia.org/wiki/Dexter_Morgan), a show you should not watch until completion.
11
12## API
13
14<!-- eslint-disable no-unused-vars -->
15
16```js
17var morgan = require('morgan')
18```
19
20### morgan(format, options)
21
22Create a new morgan logger middleware function using the given `format` and `options`.
23The `format` argument may be a string of a predefined name (see below for the names),
24a string of a format string, or a function that will produce a log entry.
25
26The `format` function will be called with three arguments `tokens`, `req`, and `res`,
27where `tokens` is an object with all defined tokens, `req` is the HTTP request and `res`
28is the HTTP response. The function is expected to return a string that will be the log
29line, or `undefined` / `null` to skip logging.
30
31#### Using a predefined format string
32
33<!-- eslint-disable no-undef -->
34
35```js
36morgan('tiny')
37```
38
39#### Using format string of predefined tokens
40
41<!-- eslint-disable no-undef -->
42
43```js
44morgan(':method :url :status :res[content-length] - :response-time ms')
45```
46
47#### Using a custom format function
48
49<!-- eslint-disable no-undef -->
50
51``` js
52morgan(function (tokens, req, res) {
53 return [
54 tokens.method(req, res),
55 tokens.url(req, res),
56 tokens.status(req, res),
57 tokens.res(req, res, 'content-length'), '-',
58 tokens['response-time'](req, res), 'ms'
59 ].join(' ')
60})
61```
62
63#### Options
64
65Morgan accepts these properties in the options object.
66
67##### immediate
68
69Write log line on request instead of response. This means that a requests will
70be logged even if the server crashes, _but data from the response (like the
71response code, content length, etc.) cannot be logged_.
72
73##### skip
74
75Function to determine if logging is skipped, defaults to `false`. This function
76will be called as `skip(req, res)`.
77
78<!-- eslint-disable no-undef -->
79
80```js
81// EXAMPLE: only log error responses
82morgan('combined', {
83 skip: function (req, res) { return res.statusCode < 400 }
84})
85```
86
87##### stream
88
89Output stream for writing log lines, defaults to `process.stdout`.
90
91#### Predefined Formats
92
93There are various pre-defined formats provided:
94
95##### combined
96
97Standard Apache combined log output.
98
99```
100:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
101```
102
103##### common
104
105Standard Apache common log output.
106
107```
108:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]
109```
110
111##### dev
112
113Concise output colored by response status for development use. The `:status`
114token will be colored red for server error codes, yellow for client error
115codes, cyan for redirection codes, and uncolored for all other codes.
116
117```
118:method :url :status :response-time ms - :res[content-length]
119```
120
121##### short
122
123Shorter than default, also including response time.
124
125```
126:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
127```
128
129##### tiny
130
131The minimal output.
132
133```
134:method :url :status :res[content-length] - :response-time ms
135```
136
137#### Tokens
138
139##### Creating new tokens
140
141To define a token, simply invoke `morgan.token()` with the name and a callback function.
142This callback function is expected to return a string value. The value returned is then
143available as ":type" in this case:
144
145<!-- eslint-disable no-undef -->
146
147```js
148morgan.token('type', function (req, res) { return req.headers['content-type'] })
149```
150
151Calling `morgan.token()` using the same name as an existing token will overwrite that
152token definition.
153
154The token function is expected to be called with the arguments `req` and `res`, representing
155the HTTP request and HTTP response. Additionally, the token can accept further arguments of
156it's choosing to customize behavior.
157
158##### :date[format]
159
160The current date and time in UTC. The available formats are:
161
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`)
165
166If no format is given, then the default is `web`.
167
168##### :http-version
169
170The HTTP version of the request.
171
172##### :method
173
174The HTTP method of the request.
175
176##### :referrer
177
178The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.
179
180##### :remote-addr
181
182The remote address of the request. This will use `req.ip`, otherwise the standard `req.connection.remoteAddress` value (socket address).
183
184##### :remote-user
185
186The user authenticated as part of Basic auth for the request.
187
188##### :req[header]
189
190The given `header` of the request. If the header is not present, the
191value will be displayed as `"-"` in the log.
192
193##### :res[header]
194
195The given `header` of the response. If the header is not present, the
196value will be displayed as `"-"` in the log.
197
198##### :response-time[digits]
199
200The time between the request coming into `morgan` and when the response
201headers are written, in milliseconds.
202
203The `digits` argument is a number that specifies the number of digits to
204include on the number, defaulting to `3`, which provides microsecond precision.
205
206##### :status
207
208The status code of the response.
209
210If the request/response cycle completes before a response was sent to the
211client (for example, the TCP socket closed prematurely by a client aborting
212the request), then the status will be empty (displayed as `"-"` in the log).
213
214##### :url
215
216The URL of the request. This will use `req.originalUrl` if exists, otherwise `req.url`.
217
218##### :user-agent
219
220The contents of the User-Agent header of the request.
221
222### morgan.compile(format)
223
224Compile a format string into a `format` function for use by `morgan`. A format string
225is a string that represents a single log line and can utilize token syntax.
226Tokens are references by `:token-name`. If tokens accept arguments, they can
227be passed using `[]`, for example: `:token-name[pretty]` would pass the string
228`'pretty'` as an argument to the token `token-name`.
229
230The 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,
233or `undefined` / `null` to skip logging.
234
235Normally formats are defined using `morgan.format(name, format)`, but for certain
236advanced uses, this compile function is directly available.
237
238## Examples
239
240### express/connect
241
242Simple app that will log all request in the Apache combined format to STDOUT
243
244```js
245var express = require('express')
246var morgan = require('morgan')
247
248var app = express()
249
250app.use(morgan('combined'))
251
252app.get('/', function (req, res) {
253 res.send('hello, world!')
254})
255```
256
257### vanilla http server
258
259Simple app that will log all request in the Apache combined format to STDOUT
260
261```js
262var finalhandler = require('finalhandler')
263var http = require('http')
264var morgan = require('morgan')
265
266// create "middleware"
267var logger = morgan('combined')
268
269http.createServer(function (req, res) {
270 var done = finalhandler(req, res)
271 logger(req, res, function (err) {
272 if (err) return done(err)
273
274 // respond to request
275 res.setHeader('content-type', 'text/plain')
276 res.end('hello, world!')
277 })
278})
279```
280
281### write logs to a file
282
283#### single file
284
285Simple app that will log all requests in the Apache combined format to the file
286`access.log`.
287
288```js
289var express = require('express')
290var fs = require('fs')
291var morgan = require('morgan')
292var path = require('path')
293
294var app = express()
295
296// create a write stream (in append mode)
297var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
298
299// setup the logger
300app.use(morgan('combined', { stream: accessLogStream }))
301
302app.get('/', function (req, res) {
303 res.send('hello, world!')
304})
305```
306
307#### log file rotation
308
309Simple app that will log all requests in the Apache combined format to one log
310file per day in the `log/` directory using the
311[rotating-file-stream module](https://www.npmjs.com/package/rotating-file-stream).
312
313```js
314var express = require('express')
315var fs = require('fs')
316var morgan = require('morgan')
317var path = require('path')
318var rfs = require('rotating-file-stream')
319
320var app = express()
321var logDirectory = path.join(__dirname, 'log')
322
323// ensure log directory exists
324fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
325
326// create a rotating write stream
327var accessLogStream = rfs('access.log', {
328 interval: '1d', // rotate daily
329 path: logDirectory
330})
331
332// setup the logger
333app.use(morgan('combined', { stream: accessLogStream }))
334
335app.get('/', function (req, res) {
336 res.send('hello, world!')
337})
338```
339
340### split / dual logging
341
342The `morgan` middleware can be used as many times as needed, enabling
343combinations like:
344
345 * Log entry on request and one on response
346 * Log all requests to file, but errors to console
347 * ... and more!
348
349Sample app that will log all requests to a file using Apache format, but
350error responses are logged to the console:
351
352```js
353var express = require('express')
354var fs = require('fs')
355var morgan = require('morgan')
356var path = require('path')
357
358var app = express()
359
360// log only 4xx and 5xx responses to console
361app.use(morgan('dev', {
362 skip: function (req, res) { return res.statusCode < 400 }
363}))
364
365// log all requests to access.log
366app.use(morgan('common', {
367 stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
368}))
369
370app.get('/', function (req, res) {
371 res.send('hello, world!')
372})
373```
374
375### use custom token formats
376
377Sample app that will use custom token formats. This adds an ID to all requests and displays it using the `:id` token.
378
379```js
380var express = require('express')
381var morgan = require('morgan')
382var uuid = require('node-uuid')
383
384morgan.token('id', function getId (req) {
385 return req.id
386})
387
388var app = express()
389
390app.use(assignId)
391app.use(morgan(':id :method :url :response-time'))
392
393app.get('/', function (req, res) {
394 res.send('hello, world!')
395})
396
397function assignId (req, res, next) {
398 req.id = uuid.v4()
399 next()
400}
401```
402
403## License
404
405[MIT](LICENSE)
406
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