pax_global_header00006660000000000000000000000064136352012210014505gustar00rootroot0000000000000052 comment=c68d2eab4c6a5d9940895a6d1614964d44358642
morgan-1.10.0/000077500000000000000000000000001363520122100130475ustar00rootroot00000000000000morgan-1.10.0/.eslintignore000066400000000000000000000000421363520122100155460ustar00rootroot00000000000000.nyc_output
coverage
node_modules
morgan-1.10.0/.eslintrc.yml000066400000000000000000000000351363520122100154710ustar00rootroot00000000000000root: true
extends: standard
morgan-1.10.0/.gitignore000066400000000000000000000001051363520122100150330ustar00rootroot00000000000000.nyc_output/
coverage/
node_modules/
npm-debug.log
package-lock.json
morgan-1.10.0/.travis.yml000066400000000000000000000060101363520122100151550ustar00rootroot00000000000000language: node_js
node_js:
- "0.8"
- "0.10"
- "0.12"
- "1.8"
- "2.5"
- "3.3"
- "4.9"
- "5.12"
- "6.17"
- "7.10"
- "8.17"
- "9.11"
- "10.19"
- "11.15"
- "12.16"
- "13.11"
cache:
directories:
- node_modules
before_install:
- |
# Setup utility functions
function node_version_lt () {
[[ "$(v "$TRAVIS_NODE_VERSION")" -lt "$(v "${1}")" ]]
}
function npm_module_installed () {
npm -lsp ls | grep -Fq "$(pwd)/node_modules/${1}:${1}@"
}
function npm_remove_module_re () {
node -e '
fs = require("fs");
p = JSON.parse(fs.readFileSync("package.json", "utf8"));
r = RegExp(process.argv[1]);
for (k in p.devDependencies) {
if (r.test(k)) delete p.devDependencies[k];
}
fs.writeFileSync("package.json", JSON.stringify(p, null, 2) + "\n");
' "$@"
}
function npm_use_module () {
node -e '
fs = require("fs");
p = JSON.parse(fs.readFileSync("package.json", "utf8"));
p.devDependencies[process.argv[1]] = process.argv[2];
fs.writeFileSync("package.json", JSON.stringify(p, null, 2) + "\n");
' "$@"
}
function v () {
tr '.' '\n' <<< "${1}" \
| awk '{ printf "%03d", $0 }' \
| sed 's/^0*//'
}
# Configure npm
- |
# Skip updating shrinkwrap / lock
npm config set shrinkwrap false
# Setup Node.js version-specific dependencies
- |
# Configure eslint for linting
if node_version_lt '8.0'; then npm_remove_module_re '^eslint(-|$)'
fi
- |
# Configure mocha for testing
if node_version_lt '0.10'; then npm_use_module 'mocha' '2.5.3'
elif node_version_lt '4.0' ; then npm_use_module 'mocha' '3.5.3'
elif node_version_lt '6.0' ; then npm_use_module 'mocha' '5.2.0'
elif node_version_lt '8.0' ; then npm_use_module 'mocha' '6.2.2'
fi
- |
# Configure nyc for coverage
if node_version_lt '0.10'; then npm_remove_module_re '^nyc$'
elif node_version_lt '4.0' ; then npm_use_module 'nyc' '10.3.2'
elif node_version_lt '6.0' ; then npm_use_module 'nyc' '11.9.0'
elif node_version_lt '8.0' ; then npm_use_module 'nyc' '14.1.1'
fi
- |
# Configure supertest for http calls
if node_version_lt '0.10'; then npm_use_module 'supertest' '1.1.0'
elif node_version_lt '4.0' ; then npm_use_module 'supertest' '2.0.0'
elif node_version_lt '6.0' ; then npm_use_module 'supertest' '3.4.2'
fi
# Update Node.js modules
- |
# Prune and rebuild node_modules
if [[ -d node_modules ]]; then
npm prune
npm rebuild
fi
script:
- |
# Run test script, depending on nyc install
if npm_module_installed 'nyc'; then npm run-script test-ci
else npm test
fi
- |
# Run linting, if eslint exists
if npm_module_installed 'eslint'; then npm run-script lint
fi
after_script:
- |
# Upload coverage to coveralls
if [[ -d .nyc_output ]]; then
npm install --save-dev coveralls@2
nyc report --reporter=text-lcov | coveralls
fi
morgan-1.10.0/HISTORY.md000066400000000000000000000124651363520122100145420ustar00rootroot000000000000001.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: safe-buffer@5.1.2
* 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
==================
* deps: debug@2.6.8
- Fix `DEBUG_MAX_ARRAY_LENGTH`
- deps: ms@2.0.0
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: ms@0.7.1
* 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
==================
* deps: on-finished@2.1.0
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
morgan-1.10.0/LICENSE000066400000000000000000000022241363520122100140540ustar00rootroot00000000000000(The MIT License)
Copyright (c) 2014 Jonathan Ong
Copyright (c) 2014-2017 Douglas Christopher Wilson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
morgan-1.10.0/README.md000066400000000000000000000254601363520122100143350ustar00rootroot00000000000000# 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](http://en.wikipedia.org/wiki/Dexter_Morgan), a show you should not watch until completion.
## API
```js
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
```js
morgan('tiny')
```
#### Using format string of predefined tokens
```js
morgan(':method :url :status :res[content-length] - :response-time ms')
```
#### Using a custom format function
``` js
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)`.
```js
// 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:
```js
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
```js
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
```js
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`.
```js
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](https://www.npmjs.com/package/rotating-file-stream).
```js
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:
```js
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.
```js
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](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
morgan-1.10.0/index.js000066400000000000000000000250151363520122100145170ustar00rootroot00000000000000/*!
* morgan
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
* @public
*/
module.exports = morgan
module.exports.compile = compile
module.exports.format = format
module.exports.token = token
/**
* Module dependencies.
* @private
*/
var auth = require('basic-auth')
var debug = require('debug')('morgan')
var deprecate = require('depd')('morgan')
var onFinished = require('on-finished')
var onHeaders = require('on-headers')
/**
* Array of CLF month names.
* @private
*/
var CLF_MONTH = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]
/**
* Default log buffer duration.
* @private
*/
var DEFAULT_BUFFER_DURATION = 1000
/**
* Create a logger middleware.
*
* @public
* @param {String|Function} format
* @param {Object} [options]
* @return {Function} middleware
*/
function morgan (format, options) {
var fmt = format
var opts = options || {}
if (format && typeof format === 'object') {
opts = format
fmt = opts.format || 'default'
// smart deprecation message
deprecate('morgan(options): use morgan(' + (typeof fmt === 'string' ? JSON.stringify(fmt) : 'format') + ', options) instead')
}
if (fmt === undefined) {
deprecate('undefined format: specify a format')
}
// output on request instead of response
var immediate = opts.immediate
// check if log entry should be skipped
var skip = opts.skip || false
// format function
var formatLine = typeof fmt !== 'function'
? getFormatFunction(fmt)
: fmt
// stream
var buffer = opts.buffer
var stream = opts.stream || process.stdout
// buffering support
if (buffer) {
deprecate('buffer option')
// flush interval
var interval = typeof buffer !== 'number'
? DEFAULT_BUFFER_DURATION
: buffer
// swap the stream
stream = createBufferStream(stream, interval)
}
return function logger (req, res, next) {
// request data
req._startAt = undefined
req._startTime = undefined
req._remoteAddress = getip(req)
// response data
res._startAt = undefined
res._startTime = undefined
// record request start
recordStartTime.call(req)
function logRequest () {
if (skip !== false && skip(req, res)) {
debug('skip request')
return
}
var line = formatLine(morgan, req, res)
if (line == null) {
debug('skip line')
return
}
debug('log request')
stream.write(line + '\n')
};
if (immediate) {
// immediate log
logRequest()
} else {
// record response start
onHeaders(res, recordStartTime)
// log when response finished
onFinished(res, logRequest)
}
next()
}
}
/**
* Apache combined log format.
*/
morgan.format('combined', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"')
/**
* Apache common log format.
*/
morgan.format('common', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]')
/**
* Default format.
*/
morgan.format('default', ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"')
deprecate.property(morgan, 'default', 'default format: use combined format')
/**
* Short format.
*/
morgan.format('short', ':remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms')
/**
* Tiny format.
*/
morgan.format('tiny', ':method :url :status :res[content-length] - :response-time ms')
/**
* dev (colored)
*/
morgan.format('dev', function developmentFormatLine (tokens, req, res) {
// get the status code if response written
var status = headersSent(res)
? res.statusCode
: undefined
// get status color
var color = status >= 500 ? 31 // red
: status >= 400 ? 33 // yellow
: status >= 300 ? 36 // cyan
: status >= 200 ? 32 // green
: 0 // no color
// get colored function
var fn = developmentFormatLine[color]
if (!fn) {
// compile
fn = developmentFormatLine[color] = compile('\x1b[0m:method :url \x1b[' +
color + 'm:status\x1b[0m :response-time ms - :res[content-length]\x1b[0m')
}
return fn(tokens, req, res)
})
/**
* request url
*/
morgan.token('url', function getUrlToken (req) {
return req.originalUrl || req.url
})
/**
* request method
*/
morgan.token('method', function getMethodToken (req) {
return req.method
})
/**
* response time in milliseconds
*/
morgan.token('response-time', function getResponseTimeToken (req, res, digits) {
if (!req._startAt || !res._startAt) {
// missing request and/or response start time
return
}
// calculate diff
var ms = (res._startAt[0] - req._startAt[0]) * 1e3 +
(res._startAt[1] - req._startAt[1]) * 1e-6
// return truncated value
return ms.toFixed(digits === undefined ? 3 : digits)
})
/**
* total time in milliseconds
*/
morgan.token('total-time', function getTotalTimeToken (req, res, digits) {
if (!req._startAt || !res._startAt) {
// missing request and/or response start time
return
}
// time elapsed from request start
var elapsed = process.hrtime(req._startAt)
// cover to milliseconds
var ms = (elapsed[0] * 1e3) + (elapsed[1] * 1e-6)
// return truncated value
return ms.toFixed(digits === undefined ? 3 : digits)
})
/**
* current date
*/
morgan.token('date', function getDateToken (req, res, format) {
var date = new Date()
switch (format || 'web') {
case 'clf':
return clfdate(date)
case 'iso':
return date.toISOString()
case 'web':
return date.toUTCString()
}
})
/**
* response status code
*/
morgan.token('status', function getStatusToken (req, res) {
return headersSent(res)
? String(res.statusCode)
: undefined
})
/**
* normalized referrer
*/
morgan.token('referrer', function getReferrerToken (req) {
return req.headers.referer || req.headers.referrer
})
/**
* remote address
*/
morgan.token('remote-addr', getip)
/**
* remote user
*/
morgan.token('remote-user', function getRemoteUserToken (req) {
// parse basic credentials
var credentials = auth(req)
// return username
return credentials
? credentials.name
: undefined
})
/**
* HTTP version
*/
morgan.token('http-version', function getHttpVersionToken (req) {
return req.httpVersionMajor + '.' + req.httpVersionMinor
})
/**
* UA string
*/
morgan.token('user-agent', function getUserAgentToken (req) {
return req.headers['user-agent']
})
/**
* request header
*/
morgan.token('req', function getRequestToken (req, res, field) {
// get header
var header = req.headers[field.toLowerCase()]
return Array.isArray(header)
? header.join(', ')
: header
})
/**
* response header
*/
morgan.token('res', function getResponseHeader (req, res, field) {
if (!headersSent(res)) {
return undefined
}
// get header
var header = res.getHeader(field)
return Array.isArray(header)
? header.join(', ')
: header
})
/**
* Format a Date in the common log format.
*
* @private
* @param {Date} dateTime
* @return {string}
*/
function clfdate (dateTime) {
var date = dateTime.getUTCDate()
var hour = dateTime.getUTCHours()
var mins = dateTime.getUTCMinutes()
var secs = dateTime.getUTCSeconds()
var year = dateTime.getUTCFullYear()
var month = CLF_MONTH[dateTime.getUTCMonth()]
return pad2(date) + '/' + month + '/' + year +
':' + pad2(hour) + ':' + pad2(mins) + ':' + pad2(secs) +
' +0000'
}
/**
* Compile a format string into a function.
*
* @param {string} format
* @return {function}
* @public
*/
function compile (format) {
if (typeof format !== 'string') {
throw new TypeError('argument format must be a string')
}
var fmt = String(JSON.stringify(format))
var js = ' "use strict"\n return ' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function (_, name, arg) {
var tokenArguments = 'req, res'
var tokenFunction = 'tokens[' + String(JSON.stringify(name)) + ']'
if (arg !== undefined) {
tokenArguments += ', ' + String(JSON.stringify(arg))
}
return '" +\n (' + tokenFunction + '(' + tokenArguments + ') || "-") + "'
})
// eslint-disable-next-line no-new-func
return new Function('tokens, req, res', js)
}
/**
* Create a basic buffering stream.
*
* @param {object} stream
* @param {number} interval
* @public
*/
function createBufferStream (stream, interval) {
var buf = []
var timer = null
// flush function
function flush () {
timer = null
stream.write(buf.join(''))
buf.length = 0
}
// write function
function write (str) {
if (timer === null) {
timer = setTimeout(flush, interval)
}
buf.push(str)
}
// return a minimal "stream"
return { write: write }
}
/**
* Define a format with the given name.
*
* @param {string} name
* @param {string|function} fmt
* @public
*/
function format (name, fmt) {
morgan[name] = fmt
return this
}
/**
* Lookup and compile a named format function.
*
* @param {string} name
* @return {function}
* @public
*/
function getFormatFunction (name) {
// lookup format
var fmt = morgan[name] || name || morgan.default
// return compiled format
return typeof fmt !== 'function'
? compile(fmt)
: fmt
}
/**
* Get request IP address.
*
* @private
* @param {IncomingMessage} req
* @return {string}
*/
function getip (req) {
return req.ip ||
req._remoteAddress ||
(req.connection && req.connection.remoteAddress) ||
undefined
}
/**
* Determine if the response headers have been sent.
*
* @param {object} res
* @returns {boolean}
* @private
*/
function headersSent (res) {
// istanbul ignore next: node.js 0.8 support
return typeof res.headersSent !== 'boolean'
? Boolean(res._header)
: res.headersSent
}
/**
* Pad number to two digits.
*
* @private
* @param {number} num
* @return {string}
*/
function pad2 (num) {
var str = String(num)
// istanbul ignore next: num is current datetime
return (str.length === 1 ? '0' : '') + str
}
/**
* Record the start time.
* @private
*/
function recordStartTime () {
this._startAt = process.hrtime()
this._startTime = new Date()
}
/**
* Define a token function with the given name,
* and callback fn(req, res).
*
* @param {string} name
* @param {function} fn
* @public
*/
function token (name, fn) {
morgan[name] = fn
return this
}
morgan-1.10.0/package.json000066400000000000000000000024041363520122100153350ustar00rootroot00000000000000{
"name": "morgan",
"description": "HTTP request logger middleware for node.js",
"version": "1.10.0",
"contributors": [
"Douglas Christopher Wilson ",
"Jonathan Ong (http://jongleberry.com)"
],
"license": "MIT",
"keywords": [
"express",
"http",
"logger",
"middleware"
],
"repository": "expressjs/morgan",
"dependencies": {
"basic-auth": "~2.0.1",
"debug": "2.6.9",
"depd": "~2.0.0",
"on-finished": "~2.3.0",
"on-headers": "~1.0.2"
},
"devDependencies": {
"eslint": "6.8.0",
"eslint-config-standard": "14.1.0",
"eslint-plugin-import": "2.20.1",
"eslint-plugin-markdown": "1.0.2",
"eslint-plugin-node": "9.2.0",
"eslint-plugin-promise": "4.2.1",
"eslint-plugin-standard": "4.0.1",
"mocha": "7.1.1",
"nyc": "15.0.0",
"split": "1.0.1",
"supertest": "4.0.2"
},
"files": [
"LICENSE",
"HISTORY.md",
"README.md",
"index.js"
],
"engines": {
"node": ">= 0.8.0"
},
"scripts": {
"lint": "eslint --plugin markdown --ext js,md .",
"test": "mocha --check-leaks --reporter spec --bail",
"test-ci": "nyc --reporter=text npm test",
"test-cov": "nyc --reporter=html --reporter=text npm test"
}
}
morgan-1.10.0/test/000077500000000000000000000000001363520122100140265ustar00rootroot00000000000000morgan-1.10.0/test/.eslintrc.yml000066400000000000000000000000231363520122100164450ustar00rootroot00000000000000env:
mocha: true
morgan-1.10.0/test/fixtures/000077500000000000000000000000001363520122100156775ustar00rootroot00000000000000morgan-1.10.0/test/fixtures/server.crt000066400000000000000000000017651363520122100177300ustar00rootroot00000000000000-----BEGIN CERTIFICATE-----
MIICwDCCAaigAwIBAgIJAJH0k+imlBVmMA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNV
BAMTCWxvY2FsaG9zdDAgFw0xODExMDUwMTM5NThaGA8yMDY4MTAyMzAxMzk1OFow
FDESMBAGA1UEAxMJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEA3nXOaU7907qgMBLKd4ZuffDPZGN11BmdLCZ68myDVde4N8kzWH7d3ggF
puqcpGb0sSko7rpf1KHw1p02YEFLRyQigbMfUOSu72BR5aUpxVbG7C87qQ8YWE/8
3eiImDaDn5tMPnUTwfh0ITCWaW3/4u3PmQB2oJQo7tF5kOMqbY8tDPeO3lX9cx84
O8BvCchgIPSFthasIRZXnrJicCH0boesA6XNKJbSfoD2hNmUVK8aFeySJ60SdAns
DNuRJEINy1eEuyHobXleaSZrlQUSPdmqYXkPkrtzHReX63LUnlmxdzn4IZVN79Tu
YlahulqoIEsaIaAxoGethhNZenytUQIDAQABoxMwETAPBgNVHREECDAGhwR/AAAB
MA0GCSqGSIb3DQEBCwUAA4IBAQAYLS/7SV+4v3s8KLfOEtCdGw4w7IkBFi3LKKns
RH74CbDZANJlI/Cc7YuZx2zP/0ux1t2VtVvvMexL4fkQsAsZtLHK5TZq6EzsAIYF
jRXXhkSCfFvxxgj52PxsMD/3tRYZQ8OWyE1f3XL7rwXmeQxOvOuSvafGTXazrSS3
fmwE53QTLv8Sepf8pTacOY1jQ7pfI4ND3/dOwuO4cc+ulELeCsQq17TEKpL1aXqN
5gGKe02u9Otq2E39+2FaI11IKUg3EUWKezFlHrxEr32pLPHMq/arVFUOApTgLekB
UPGac0c4lowHqCXXQBQusihQtnY0JKbzwWnW4UBk5apGSHWR
-----END CERTIFICATE-----
morgan-1.10.0/test/fixtures/server.key000066400000000000000000000032501363520122100177170ustar00rootroot00000000000000-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDedc5pTv3TuqAw
Esp3hm598M9kY3XUGZ0sJnrybINV17g3yTNYft3eCAWm6pykZvSxKSjuul/UofDW
nTZgQUtHJCKBsx9Q5K7vYFHlpSnFVsbsLzupDxhYT/zd6IiYNoOfm0w+dRPB+HQh
MJZpbf/i7c+ZAHaglCju0XmQ4yptjy0M947eVf1zHzg7wG8JyGAg9IW2FqwhFlee
smJwIfRuh6wDpc0oltJ+gPaE2ZRUrxoV7JInrRJ0CewM25EkQg3LV4S7IehteV5p
JmuVBRI92apheQ+Su3MdF5frctSeWbF3OfghlU3v1O5iVqG6WqggSxohoDGgZ62G
E1l6fK1RAgMBAAECggEAHKHG/lDXZI/pnCZe/sFDqVv8JWyTtsfRLeSKAHes87h/
ElcID8TMY45ew9wAazyBE+g7R3afbOum5sh3Pi5JNQ/WjSDzz+KPDWo1QDxgwvBn
S/DMWfcCaCNrZVhPdF/X0wwW5RcGgvmqYLczNMCepaN8C7I+km5fUlWNsvM5+72r
UwagsYzb4H6FeR5UnXDVoHXhFw/rIgiTqicv6Dg4y177Jev9RPlT9F+RKBVZE1+u
vB+v66yoN1w2if+wBQICWnqKu0YK+gL31hiFjlbd2SlFcHDl3U41FDdhEk7im13B
1e400/Fu4MYEmWgGJj82Mm+FBs6jh+CbcjTj4G7trQKBgQD3jswnm9RU21YaNW8N
mfEXFS8j/cuzJe8Va8swrPh/8L/4L6pdfjrfpA0wXq/SuIiz+xZgszfVlSD1Rf+t
IcbW71OhahIRglvFRbqk8NYX6uzniWE4IpFBgt9o8HaI8dvfIJNUy3Pc2c6ZgzCc
ZBQbwic65K7VHYVlZ+NANKgN7wKBgQDmC+d9OkPSvOvt7miD5AlUepfHmxDYz9Kf
UezOqHsI4i8O0cr2PL+HPgOOEsjgB2IIZAcGSV/IqT0Ys4y1KLDU0KMgao//tPFp
4cN/SxgeaK6WLZP+OAvFi2UXpqUaeCCM/7KaaLoi/WoMqCLJcuJpO8MxsDikg/jp
rNoOANI4vwKBgQCiBOdAlRAmaVa02HvSHwpW3Rp5J8WFfjI3htD5Dnuk4GADgs6x
WcgWTjwDiDTyaKuvf4lpyGGme2+Slzl6ijyktwW5Ar7IjtSZC8XX5Xd5N9vMvXDP
WHBQu+KTv60Ue5Y3Ng621GEEDdjVR7Ms56Lxd+RM+xYhjKydbZyhjNTgKQKBgA9K
U0Sbjs5/CB90bTX2/jfDPjtiLyh6B8HXLCpAQI1Cm2Ycw6TCPOi8Ungq/3cEhpuQ
KndcgSVROmJd7MhNwBMlGvKYoqGYYUNsYhYf46aBxrjspp2LFB05OqrrxKWRvngg
trpUo6qXtWjJ9CX3oNzlv/+ZeupUa0L83jF4FID5AoGAE3Y42ixUqv86R8ZtK02z
FA86hT01M2WW7YJyePWQ0/x64Ym3seTzutDFCtEpkAbt+lu/YaCRTz8/NjF0KYzN
xJ4jjeiccbqslLuVMSfpY7LAm+udn+PsOpL5ezCzwgnFkZAVSKV+VDdENkQCtMaL
zGVrPC/Lt2tJiLSllgFace0=
-----END PRIVATE KEY-----
morgan-1.10.0/test/morgan.js000066400000000000000000001326611363520122100156600ustar00rootroot00000000000000
process.env.NO_DEPRECATION = 'morgan'
var assert = require('assert')
var fs = require('fs')
var http = require('http')
var https = require('https')
var join = require('path').join
var morgan = require('..')
var request = require('supertest')
var split = require('split')
describe('morgan()', function () {
describe('arguments', function () {
it('should use default format', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert(res.text.length > 0)
assert.strictEqual(line.substr(0, res.text.length), res.text)
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(undefined, { stream: stream }))
.get('/')
.expect(200, cb)
})
describe('format', function () {
it('should accept format as format name', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert(/^GET \/ 200 - - \d+\.\d{3} ms$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer('tiny', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should accept format as format string', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'GET /')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':method :url', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should accept format as function', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'GET / 200')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
function format (tokens, req, res) {
return [req.method, req.url, res.statusCode].join(' ')
}
request(createServer(format, { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should reject format as bool', function () {
assert.throws(createServer.bind(null, true), /argument format/)
})
describe('back-compat', function () {
it('should accept options object', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert(res.text.length > 0)
assert.strictEqual(line.substr(0, res.text.length), res.text)
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer({ stream: stream }))
.get('/')
.expect(200, cb)
})
it('should accept format in options for back-compat', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'GET /')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer({ format: ':method :url', stream: stream }))
.get('/')
.expect(200, cb)
})
it('should accept format function in options for back-compat', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'apple')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
function format () {
return 'apple'
}
request(createServer({ format: format, stream: stream }))
.get('/')
.expect(200, cb)
})
})
})
describe('stream', function () {
beforeEach(function () {
this.stdout = process.stdout
})
afterEach(function () {
Object.defineProperty(process, 'stdout', {
value: this.stdout
})
})
it('should default to process.stdout', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert(res.text.length > 0)
assert.strictEqual(line.substr(0, res.text.length), res.text)
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
Object.defineProperty(process, 'stdout', {
value: stream
})
request(createServer(undefined, { stream: undefined }))
.get('/')
.expect(200, cb)
})
it('should set stream to write logs to', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert(res.text.length > 0)
assert.strictEqual(line.substr(0, res.text.length), res.text)
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(undefined, { stream: stream }))
.get('/')
.expect(200, cb)
})
})
})
describe('tokens', function () {
describe(':date', function () {
it('should get current date in "web" format by default', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(/^\w{3}, \d{2} \w{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':date', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should get current date in "clf" format', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(/^\d{2}\/\w{3}\/\d{4}:\d{2}:\d{2}:\d{2} \+0000$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':date[clf]', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should get current date in "iso" format', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':date[iso]', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should get current date in "web" format', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(/^\w{3}, \d{2} \w{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':date[web]', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should be blank for unknown format', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '-')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':date[bogus]', { stream: stream }))
.get('/')
.expect(200, cb)
})
})
describe(':http-version', function () {
it('should be 1.0 or 1.1', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(/^1\.[01]$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':http-version', { stream: stream }))
.get('/')
.expect(200, cb)
})
})
describe(':req', function () {
it('should get request properties', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'me')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':req[x-from-string]', { stream: stream }))
.get('/')
.set('x-from-string', 'me')
.expect(200, cb)
})
it('should display all values of array headers', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'foo=bar, fizz=buzz')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':req[set-cookie]', { stream: stream }))
.get('/')
.set('Set-Cookie', ['foo=bar', 'fizz=buzz'])
.expect(200, cb)
})
})
describe(':res', function () {
it('should get response properties', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'true')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':res[x-sent]', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should display all values of array headers', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'foo, bar')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':res[x-keys]', { stream: stream }, function (req, res, next) {
res.setHeader('X-Keys', ['foo', 'bar'])
next()
})
request(server)
.get('/')
.expect('X-Keys', 'foo, bar')
.expect(200, cb)
})
})
describe(':remote-addr', function () {
it('should get remote address', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(res.text.length > 0)
assert.strictEqual(line, res.text)
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':remote-addr', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should use req.ip if there', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '10.0.0.1')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':remote-addr', { stream: stream }, null, function (req) {
req.ip = '10.0.0.1'
})
request(server)
.get('/')
.expect(200, cb)
})
it('should work on https server', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(res.text.length > 0)
assert.strictEqual(line, res.text)
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createSecureServer(':remote-addr', { stream: stream })
request(server)
.get('/')
.ca(server.cert)
.expect(200, cb)
})
it('should work when connection: close', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(res.text.length > 0)
assert.strictEqual(line, res.text)
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':remote-addr', { stream: stream }))
.get('/')
.set('Connection', 'close')
.expect(200, cb)
})
it('should work when connection: keep-alive', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(res.text.length > 0)
assert.strictEqual(line, res.text)
res.req.connection.destroy()
server.close(done)
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':remote-addr', { stream: stream }, function (req, res, next) {
delete req._remoteAddress
next()
})
request(server.listen())
.get('/')
.set('Connection', 'keep-alive')
.expect(200, cb)
})
it('should work when req.ip is a getter', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '10.0.0.1')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':remote-addr', { stream: stream }, null, function (req) {
Object.defineProperty(req, 'ip', {
get: function () { return req.connection.remoteAddress ? '10.0.0.1' : undefined }
})
})
request(server)
.get('/')
.set('Connection', 'close')
.expect(200, cb)
})
it('should not fail if req.connection missing', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(res.text.length > 0)
assert.strictEqual(line, res.text)
res.req.connection.destroy()
server.close(done)
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':remote-addr', { stream: stream }, null, function (req) {
delete req.connection
})
request(server.listen())
.get('/')
.set('Connection', 'keep-alive')
.expect(200, cb)
})
})
describe(':remote-user', function () {
it('should be empty if none present', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '-')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':remote-user', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should support Basic authorization', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'tj')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':remote-user', { stream: stream }))
.get('/')
.set('Authorization', 'Basic dGo6')
.expect(200, cb)
})
it('should be empty for empty Basic authorization user', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '-')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':remote-user', { stream: stream }))
.get('/')
.set('Authorization', 'Basic Og==')
.expect(200, cb)
})
})
describe(':response-time', function () {
it('should be in milliseconds', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
var end = Date.now()
var ms = parseFloat(line)
assert(ms > 0)
assert(ms < end - start + 1)
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var start = Date.now()
request(createServer(':response-time', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should have three digits by default', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(/^[0-9]+\.[0-9]{3}$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':response-time', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should have five digits with argument "5"', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(/^[0-9]+\.[0-9]{5}$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':response-time[5]', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should have no digits with argument "0"', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(/^[0-9]+$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':response-time[0]', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should not include response write time', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
var end = Date.now()
var ms = parseFloat(line)
assert(ms > 0)
assert(ms < end - start + 1)
assert(ms < write - start + 1)
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':response-time', { stream: stream }, function (req, res) {
res.write('hello, ')
write = Date.now()
setTimeout(function () {
res.end('world!')
}, 50)
})
var start = Date.now()
var write = null
request(server)
.get('/')
.expect(200, cb)
})
it('should be empty without hidden property', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '-')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':response-time', { stream: stream }, function (req, res, next) {
delete req._startAt
next()
})
request(server)
.get('/')
.expect(200, cb)
})
it('should be empty before response', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '-')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':response-time', {
immediate: true,
stream: stream
})
request(server)
.get('/')
.expect(200, cb)
})
it('should be empty if morgan invoked after response sent', function (done) {
var cb = after(3, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '-')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var logger = morgan(':response-time', {
immediate: true,
stream: stream
})
var server = http.createServer(function (req, res) {
setTimeout(function () {
logger(req, res, cb)
}, 10)
res.end()
})
request(server)
.get('/')
.expect(200, cb)
})
})
describe(':status', function () {
it('should get response status', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, String(res.statusCode))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':status', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should not exist before response sent', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '-')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':status', {
immediate: true,
stream: stream
})
request(server)
.get('/')
.expect(200, cb)
})
it('should not exist for aborted request', function (done) {
var stream = createLineStream(function (line) {
assert.strictEqual(line, '-')
server.close(done)
})
var server = createServer(':status', { stream: stream }, function () {
test.abort()
})
var test = request(server).post('/')
test.write('0')
})
})
describe(':total-time', function () {
it('should be in milliseconds', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
var end = Date.now()
var ms = parseFloat(line)
assert(ms > 0)
assert(ms < end - start + 1)
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var start = Date.now()
request(createServer(':total-time', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should have three digits by default', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(/^[0-9]+\.[0-9]{3}$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':total-time', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should have five digits with argument "5"', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(/^[0-9]+\.[0-9]{5}$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':total-time[5]', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should have no digits with argument "0"', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.ok(/^[0-9]+$/.test(line))
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':total-time[0]', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should include response write time', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
var end = Date.now()
var ms = parseFloat(line)
assert(ms > 0)
assert(ms > write - start - 1)
assert(ms < end - start + 1)
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':total-time', { stream: stream }, function (req, res) {
res.write('hello, ')
write = Date.now()
setTimeout(function () {
res.end('world!')
}, 50)
})
var start = Date.now()
var write = null
request(server)
.get('/')
.expect(200, cb)
})
it('should be empty without hidden property', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '-')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':total-time', { stream: stream }, function (req, res, next) {
delete req._startAt
next()
})
request(server)
.get('/')
.expect(200, cb)
})
it('should be empty before response', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '-')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':total-time', {
immediate: true,
stream: stream
})
request(server)
.get('/')
.expect(200, cb)
})
it('should be empty if morgan invoked after response sent', function (done) {
var cb = after(3, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '-')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var logger = morgan(':total-time', {
immediate: true,
stream: stream
})
var server = http.createServer(function (req, res) {
setTimeout(function () {
logger(req, res, cb)
}, 10)
res.end()
})
request(server)
.get('/')
.expect(200, cb)
})
})
describe(':url', function () {
it('should get request URL', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '/foo')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':url', { stream: stream }))
.get('/foo')
.expect(200, cb)
})
it('should use req.originalUrl if exists', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '/bar')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':url', { stream: stream }, function (req, res, next) {
req.originalUrl = '/bar'
next()
})
request(server)
.get('/')
.expect(200, cb)
})
it('should not exist for aborted request', function (done) {
var stream = createLineStream(function (line) {
assert.strictEqual(line, '-')
server.close(done)
})
var server = createServer(':status', { stream: stream }, function () {
test.abort()
})
var test = request(server).post('/')
test.write('0')
})
})
})
describe('formats', function () {
describe('a function', function () {
it('should log result of function', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'GET / 200')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
function format (tokens, req, res) {
return [req.method, req.url, res.statusCode].join(' ')
}
request(createServer(format, { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should not log for undefined return', function (done) {
var stream = createLineStream(function () {
throw new Error('should not log line')
})
function format (tokens, req, res) {
return undefined
}
request(createServer(format, { stream: stream }))
.get('/')
.expect(200, done)
})
it('should not log for null return', function (done) {
var stream = createLineStream(function () {
throw new Error('should not log line')
})
function format (tokens, req, res) {
return null
}
request(createServer(format, { stream: stream }))
.get('/')
.expect(200, done)
})
})
describe('a string', function () {
it('should accept format as format string of tokens', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'GET /')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer(':method :url', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should accept text mixed with tokens', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'method=GET url=/')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer('method=:method url=:url', { stream: stream }))
.get('/')
.expect(200, cb)
})
it('should accept special characters', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'LOCAL\\tobi "GET /" 200')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer('LOCAL\\:remote-user ":method :url" :status', { stream: stream }))
.get('/')
.set('Authorization', 'Basic dG9iaTpsb2tp')
.expect(200, cb)
})
})
describe('combined', function () {
it('should match expectations', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
var masked = line.replace(/\d{2}\/\w{3}\/\d{4}:\d{2}:\d{2}:\d{2} \+0000/, '_timestamp_')
assert.strictEqual(masked, res.text + ' - tj [_timestamp_] "GET / HTTP/1.1" 200 - "http://localhost/" "my-ua"')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer('combined', { stream: stream }))
.get('/')
.set('Authorization', 'Basic dGo6')
.set('Referer', 'http://localhost/')
.set('User-Agent', 'my-ua')
.expect(200, cb)
})
})
describe('common', function () {
it('should match expectations', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
var masked = line.replace(/\d{2}\/\w{3}\/\d{4}:\d{2}:\d{2}:\d{2} \+0000/, '_timestamp_')
assert.strictEqual(masked, res.text + ' - tj [_timestamp_] "GET / HTTP/1.1" 200 -')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer('common', { stream: stream }))
.get('/')
.set('Authorization', 'Basic dGo6')
.expect(200, cb)
})
})
describe('default', function () {
it('should match expectations', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
var masked = line.replace(/\w+, \d+ \w+ \d+ \d+:\d+:\d+ \w+/, '_timestamp_')
assert.strictEqual(masked, res.text + ' - tj [_timestamp_] "GET / HTTP/1.1" 200 - "http://localhost/" "my-ua"')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer('default', { stream: stream }))
.get('/')
.set('Authorization', 'Basic dGo6')
.set('Referer', 'http://localhost/')
.set('User-Agent', 'my-ua')
.expect(200, cb)
})
})
describe('dev', function () {
it('should not color 1xx', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line.substr(0, 36), '_color_0_GET / _color_0_102_color_0_')
assert.strictEqual(line.substr(-9), '_color_0_')
done()
})
var stream = createColorLineStream(function onLine (line) {
cb(null, null, line)
})
var server = createServer('dev', { stream: stream }, function (req, res, next) {
res.statusCode = 102
next()
})
request(server)
.get('/')
.expect(102, function (err, res) {
if (err && err.code === 'ECONNRESET') {
// finishing response with 1xx is invalid http
// but node.js server lets the server do this, so
// morgan needs to test in this condition even if
// the http client doesn't like it
err = null
}
cb(err, res)
})
})
it('should color 2xx green', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line.substr(0, 37), '_color_0_GET / _color_32_200_color_0_')
assert.strictEqual(line.substr(-9), '_color_0_')
done()
})
var stream = createColorLineStream(function onLine (line) {
cb(null, null, line)
})
var server = createServer('dev', { stream: stream }, function (req, res, next) {
res.statusCode = 200
next()
})
request(server)
.get('/')
.expect(200, cb)
})
it('should color 3xx cyan', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line.substr(0, 37), '_color_0_GET / _color_36_300_color_0_')
assert.strictEqual(line.substr(-9), '_color_0_')
done()
})
var stream = createColorLineStream(function onLine (line) {
cb(null, null, line)
})
var server = createServer('dev', { stream: stream }, function (req, res, next) {
res.statusCode = 300
next()
})
request(server)
.get('/')
.expect(300, cb)
})
it('should color 4xx yelow', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line.substr(0, 37), '_color_0_GET / _color_33_400_color_0_')
assert.strictEqual(line.substr(-9), '_color_0_')
done()
})
var stream = createColorLineStream(function onLine (line) {
cb(null, null, line)
})
var server = createServer('dev', { stream: stream }, function (req, res, next) {
res.statusCode = 400
next()
})
request(server)
.get('/')
.expect(400, cb)
})
it('should color 5xx red', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line.substr(0, 37), '_color_0_GET / _color_31_500_color_0_')
assert.strictEqual(line.substr(-9), '_color_0_')
done()
})
var stream = createColorLineStream(function onLine (line) {
cb(null, null, line)
})
var server = createServer('dev', { stream: stream }, function (req, res, next) {
res.statusCode = 500
next()
})
request(server)
.get('/')
.expect(500, cb)
})
describe('with "immediate: true" option', function () {
it('should not have color or response values', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, '_color_0_GET / _color_0_-_color_0_ - ms - -_color_0_')
done()
})
var stream = createColorLineStream(function onLine (line) {
cb(null, null, line)
})
var server = createServer('dev', {
immediate: true,
stream: stream
})
request(server)
.get('/')
.expect(200, cb)
})
})
})
describe('short', function () {
it('should match expectations', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
var masked = line.replace(/\d+\.\d{3} ms/, '_timer_')
assert.strictEqual(masked, res.text + ' tj GET / HTTP/1.1 200 - - _timer_')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer('short', { stream: stream }))
.get('/')
.set('Authorization', 'Basic dGo6')
.expect(200, cb)
})
})
describe('tiny', function () {
it('should match expectations', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
var masked = line.replace(/\d+\.\d{3} ms/, '_timer_')
assert.strictEqual(masked, 'GET / 200 - - _timer_')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
request(createServer('tiny', { stream: stream }))
.get('/')
.expect(200, cb)
})
})
})
describe('with buffer option', function () {
it('should flush log periodically', function (done) {
var cb = after(2, function (err, res, log) {
if (err) return done(err)
assert.strictEqual(log, 'GET /first\nGET /second\n')
assert.ok(Date.now() - time >= 1000)
assert.ok(Date.now() - time <= 1100)
done()
})
var server = createServer(':method :url', {
buffer: true,
stream: { write: writeLog }
})
var time = Date.now()
function writeLog (log) {
cb(null, null, log)
}
request(server)
.get('/first')
.expect(200, function (err) {
if (err) return cb(err)
request(server)
.get('/second')
.expect(200, cb)
})
})
it('should accept custom interval', function (done) {
var cb = after(2, function (err, res, log) {
if (err) return done(err)
assert.strictEqual(log, 'GET /first\nGET /second\n')
assert.ok(Date.now() - time >= 200)
assert.ok(Date.now() - time <= 300)
done()
})
var server = createServer(':method :url', {
buffer: 200,
stream: { write: writeLog }
})
var time = Date.now()
function writeLog (log) {
cb(null, null, log)
}
request(server)
.get('/first')
.expect(200, function (err) {
if (err) return cb(err)
request(server)
.get('/second')
.expect(200, cb)
})
})
})
describe('with immediate option', function () {
it('should not have value for :res', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'GET / -')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':method :url :res[x-sent]', {
immediate: true,
stream: stream
})
request(server)
.get('/')
.expect(200, cb)
})
it('should not have value for :response-time', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'GET / -')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':method :url :response-time', {
immediate: true,
stream: stream
})
request(server)
.get('/')
.expect(200, cb)
})
it('should not have value for :status', function (done) {
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'GET / -')
done()
})
var stream = createLineStream(function (line) {
cb(null, null, line)
})
var server = createServer(':method :url :status', {
immediate: true,
stream: stream
})
request(server)
.get('/')
.expect(200, cb)
})
it('should log before response', function (done) {
var lineLogged = false
var cb = after(2, function (err, res, line) {
if (err) return done(err)
assert.strictEqual(line, 'GET / -')
done()
})
var stream = createLineStream(function (line) {
lineLogged = true
cb(null, null, line)
})
var server = createServer(':method :url :res[x-sent]', { immediate: true, stream: stream }, function (req, res, next) {
assert.ok(lineLogged)
next()
})
request(server)
.get('/')
.expect(200, cb)
})
})
describe('with skip option', function () {
it('should be able to skip based on request', function (done) {
var stream = createLineStream(function () {
throw new Error('should not log line')
})
function skip (req) {
return req.url.indexOf('skip=true') !== -1
}
request(createServer({ format: 'default', skip: skip, stream: stream }))
.get('/?skip=true')
.set('Connection', 'close')
.expect(200, done)
})
it('should be able to skip based on response', function (done) {
var stream = createLineStream(function () {
throw new Error('should not log line')
})
function skip (req, res) {
return res.statusCode === 200
}
request(createServer({ format: 'default', skip: skip, stream: stream }))
.get('/')
.expect(200, done)
})
})
})
describe('morgan.compile(format)', function () {
describe('arguments', function () {
describe('format', function () {
it('should be required', function () {
assert.throws(morgan.compile.bind(morgan), /argument format/)
})
it('should reject functions', function () {
assert.throws(morgan.compile.bind(morgan, function () {}), /argument format/)
})
it('should reject numbers', function () {
assert.throws(morgan.compile.bind(morgan, 42), /argument format/)
})
it('should compile a string into a function', function () {
var fn = morgan.compile(':method')
assert.ok(typeof fn === 'function')
assert.ok(fn.length === 3)
})
})
})
})
function after (count, callback) {
var args = new Array(3)
var i = 0
return function (err, arg1, arg2) {
assert.ok(i++ < count, 'callback called ' + count + ' times')
args[0] = args[0] || err
args[1] = args[1] || arg1
args[2] = args[2] || arg2
if (count === i) {
callback.apply(null, args)
}
}
}
function createColorLineStream (callback) {
return createLineStream(function onLine (line) {
callback(expandColorCharacters(line))
})
}
function createLineStream (callback) {
return split().on('data', callback)
}
function createRequestListener (format, opts, fn, fn1) {
var logger = morgan(format, opts)
var middle = fn || noopMiddleware
return function onRequest (req, res) {
// prior alterations
if (fn1) {
fn1(req, res)
}
logger(req, res, function onNext (err) {
// allow req, res alterations
middle(req, res, function onDone () {
if (err) {
res.statusCode = 500
res.end(err.message)
}
res.setHeader('X-Sent', 'true')
res.end((req.connection && req.connection.remoteAddress) || '-')
})
})
}
}
function createSecureServer (format, opts, fn, fn1) {
var cert = fs.readFileSync(join(__dirname, 'fixtures', 'server.crt'), 'ascii')
var key = fs.readFileSync(join(__dirname, 'fixtures', 'server.key'), 'ascii')
return https.createServer({ cert: cert, key: key })
.on('request', createRequestListener(format, opts, fn, fn1))
}
function createServer (format, opts, fn, fn1) {
return http.createServer()
.on('request', createRequestListener(format, opts, fn, fn1))
}
function expandColorCharacters (str) {
// eslint-disable-next-line no-control-regex
return str.replace(/\x1b\[(\d+)m/g, '_color_$1_')
}
function noopMiddleware (req, res, next) {
next()
}