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 |
|
8 | HTTP 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 |
|
15 |
|
16 | ```js
|
17 | var morgan = require('morgan')
|
18 | ```
|
19 |
|
20 | ### morgan(format, options)
|
21 |
|
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.
|
25 |
|
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.
|
30 |
|
31 | #### Using a predefined format string
|
32 |
|
33 |
|
34 |
|
35 | ```js
|
36 | morgan('tiny')
|
37 | ```
|
38 |
|
39 | #### Using format string of predefined tokens
|
40 |
|
41 |
|
42 |
|
43 | ```js
|
44 | morgan(':method :url :status :res[content-length] - :response-time ms')
|
45 | ```
|
46 |
|
47 | #### Using a custom format function
|
48 |
|
49 |
|
50 |
|
51 | ``` js
|
52 | morgan(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 |
|
65 | Morgan accepts these properties in the options object.
|
66 |
|
67 | ##### immediate
|
68 |
|
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_.
|
72 |
|
73 | ##### skip
|
74 |
|
75 | Function to determine if logging is skipped, defaults to `false`. This function
|
76 | will be called as `skip(req, res)`.
|
77 |
|
78 |
|
79 |
|
80 | ```js
|
81 | // EXAMPLE: only log error responses
|
82 | morgan('combined', {
|
83 | skip: function (req, res) { return res.statusCode < 400 }
|
84 | })
|
85 | ```
|
86 |
|
87 | ##### stream
|
88 |
|
89 | Output stream for writing log lines, defaults to `process.stdout`.
|
90 |
|
91 | #### Predefined Formats
|
92 |
|
93 | There are various pre-defined formats provided:
|
94 |
|
95 | ##### combined
|
96 |
|
97 | Standard 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 |
|
105 | Standard 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 |
|
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.
|
116 |
|
117 | ```
|
118 | :method :url :status :response-time ms - :res[content-length]
|
119 | ```
|
120 |
|
121 | ##### short
|
122 |
|
123 | Shorter 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 |
|
131 | The minimal output.
|
132 |
|
133 | ```
|
134 | :method :url :status :res[content-length] - :response-time ms
|
135 | ```
|
136 |
|
137 | #### Tokens
|
138 |
|
139 | ##### Creating new tokens
|
140 |
|
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:
|
144 |
|
145 |
|
146 |
|
147 | ```js
|
148 | morgan.token('type', function (req, res) { return req.headers['content-type'] })
|
149 | ```
|
150 |
|
151 | Calling `morgan.token()` using the same name as an existing token will overwrite that
|
152 | token definition.
|
153 |
|
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.
|
157 |
|
158 | ##### :date[format]
|
159 |
|
160 | The 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 |
|
166 | If no format is given, then the default is `web`.
|
167 |
|
168 | ##### :http-version
|
169 |
|
170 | The HTTP version of the request.
|
171 |
|
172 | ##### :method
|
173 |
|
174 | The HTTP method of the request.
|
175 |
|
176 | ##### :referrer
|
177 |
|
178 | The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.
|
179 |
|
180 | ##### :remote-addr
|
181 |
|
182 | The remote address of the request. This will use `req.ip`, otherwise the standard `req.connection.remoteAddress` value (socket address).
|
183 |
|
184 | ##### :remote-user
|
185 |
|
186 | The user authenticated as part of Basic auth for the request.
|
187 |
|
188 | ##### :req[header]
|
189 |
|
190 | The given `header` of the request. If the header is not present, the
|
191 | value will be displayed as `"-"` in the log.
|
192 |
|
193 | ##### :res[header]
|
194 |
|
195 | The given `header` of the response. If the header is not present, the
|
196 | value will be displayed as `"-"` in the log.
|
197 |
|
198 | ##### :response-time[digits]
|
199 |
|
200 | The time between the request coming into `morgan` and when the response
|
201 | headers are written, in milliseconds.
|
202 |
|
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.
|
205 |
|
206 | ##### :status
|
207 |
|
208 | The status code of the response.
|
209 |
|
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).
|
213 |
|
214 | ##### :url
|
215 |
|
216 | The URL of the request. This will use `req.originalUrl` if exists, otherwise `req.url`.
|
217 |
|
218 | ##### :user-agent
|
219 |
|
220 | The contents of the User-Agent header of the request.
|
221 |
|
222 | ### morgan.compile(format)
|
223 |
|
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`.
|
229 |
|
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.
|
234 |
|
235 | Normally formats are defined using `morgan.format(name, format)`, but for certain
|
236 | advanced uses, this compile function is directly available.
|
237 |
|
238 | ## Examples
|
239 |
|
240 | ### express/connect
|
241 |
|
242 | Simple app that will log all request in the Apache combined format to STDOUT
|
243 |
|
244 | ```js
|
245 | var express = require('express')
|
246 | var morgan = require('morgan')
|
247 |
|
248 | var app = express()
|
249 |
|
250 | app.use(morgan('combined'))
|
251 |
|
252 | app.get('/', function (req, res) {
|
253 | res.send('hello, world!')
|
254 | })
|
255 | ```
|
256 |
|
257 | ### vanilla http server
|
258 |
|
259 | Simple app that will log all request in the Apache combined format to STDOUT
|
260 |
|
261 | ```js
|
262 | var finalhandler = require('finalhandler')
|
263 | var http = require('http')
|
264 | var morgan = require('morgan')
|
265 |
|
266 | // create "middleware"
|
267 | var logger = morgan('combined')
|
268 |
|
269 | http.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 |
|
285 | Simple app that will log all requests in the Apache combined format to the file
|
286 | `access.log`.
|
287 |
|
288 | ```js
|
289 | var express = require('express')
|
290 | var fs = require('fs')
|
291 | var morgan = require('morgan')
|
292 | var path = require('path')
|
293 |
|
294 | var app = express()
|
295 |
|
296 | // create a write stream (in append mode)
|
297 | var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
|
298 |
|
299 | // setup the logger
|
300 | app.use(morgan('combined', { stream: accessLogStream }))
|
301 |
|
302 | app.get('/', function (req, res) {
|
303 | res.send('hello, world!')
|
304 | })
|
305 | ```
|
306 |
|
307 | #### log file rotation
|
308 |
|
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).
|
312 |
|
313 | ```js
|
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')
|
319 |
|
320 | var app = express()
|
321 | var logDirectory = path.join(__dirname, 'log')
|
322 |
|
323 | // ensure log directory exists
|
324 | fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
|
325 |
|
326 | // create a rotating write stream
|
327 | var accessLogStream = rfs('access.log', {
|
328 | interval: '1d', // rotate daily
|
329 | path: logDirectory
|
330 | })
|
331 |
|
332 | // setup the logger
|
333 | app.use(morgan('combined', { stream: accessLogStream }))
|
334 |
|
335 | app.get('/', function (req, res) {
|
336 | res.send('hello, world!')
|
337 | })
|
338 | ```
|
339 |
|
340 | ### split / dual logging
|
341 |
|
342 | The `morgan` middleware can be used as many times as needed, enabling
|
343 | combinations 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 |
|
349 | Sample app that will log all requests to a file using Apache format, but
|
350 | error responses are logged to the console:
|
351 |
|
352 | ```js
|
353 | var express = require('express')
|
354 | var fs = require('fs')
|
355 | var morgan = require('morgan')
|
356 | var path = require('path')
|
357 |
|
358 | var app = express()
|
359 |
|
360 | // log only 4xx and 5xx responses to console
|
361 | app.use(morgan('dev', {
|
362 | skip: function (req, res) { return res.statusCode < 400 }
|
363 | }))
|
364 |
|
365 | // log all requests to access.log
|
366 | app.use(morgan('common', {
|
367 | stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
|
368 | }))
|
369 |
|
370 | app.get('/', function (req, res) {
|
371 | res.send('hello, world!')
|
372 | })
|
373 | ```
|
374 |
|
375 | ### use custom token formats
|
376 |
|
377 | Sample app that will use custom token formats. This adds an ID to all requests and displays it using the `:id` token.
|
378 |
|
379 | ```js
|
380 | var express = require('express')
|
381 | var morgan = require('morgan')
|
382 | var uuid = require('node-uuid')
|
383 |
|
384 | morgan.token('id', function getId (req) {
|
385 | return req.id
|
386 | })
|
387 |
|
388 | var app = express()
|
389 |
|
390 | app.use(assignId)
|
391 | app.use(morgan(':id :method :url :response-time'))
|
392 |
|
393 | app.get('/', function (req, res) {
|
394 | res.send('hello, world!')
|
395 | })
|
396 |
|
397 | function 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
|