diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/.travis.yml b/.travis.yml index 05d299e..2197832 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,3 @@ language: node_js node_js: - - "0.10" - - "0.11" + - "node" diff --git a/index.js b/index.js index 335a24f..7873f0c 100644 --- a/index.js +++ b/index.js @@ -1,32 +1,52 @@ -var uuid = require('uuid'); +const uuid = require('uuid'); -module.exports = function logRequest(options) { - var logger = options.logger; - var headerName = options.headerName || 'x-request-id'; +module.exports = function logRequest({headerName='x-request-id', logger}={}) { return function (req, res, next) { - var id = req.headers[headerName] || uuid.v4(); - var now = Date.now(); - var startOpts = {req: req}; + const id = req.headers[headerName] || uuid.v4(); - req.log = logger.child({ + const log = logger.child({ type: 'request', id: id, serializers: logger.constructor.stdSerializers }); + // Request + req.log = log + + const startOpts = {req: req}; + if (req.body) { startOpts.body = req.body; } + else if (req.text) { + startOpts.text = req.text; + } + log.info(startOpts, 'start request'); + + // Response res.setHeader(headerName, id); - req.log.info(startOpts, 'start request'); - - var time = process.hrtime(); + let res_body + const res_send = res.send + res.send = function(body) + { + res_body = body + + res_send.call(res, body) + } + + const time = process.hrtime(); res.on('finish', function responseSent() { - var diff = process.hrtime(time); - req.log.info({res: res, duration: diff[0] * 1e3 + diff[1] * 1e-6}, 'end request'); + const diff = process.hrtime(time); + const endOpts = {res: res, duration: diff[0] * 1e3 + diff[1] * 1e-6} + + if (res_body !== undefined) { + endOpts.body = res_body; + } + + log.info(endOpts, 'end request'); }); next(); diff --git a/package.json b/package.json index c7175b5..7b7963c 100644 --- a/package.json +++ b/package.json @@ -4,13 +4,13 @@ "description": "Request, response logger middleware using bunyan. Also provides request<>response duration.", "main": "index.js", "dependencies": { - "uuid": "^2.0.1" + "uuid": "^3.2.1" }, "devDependencies": { - "body-parser": "^1.9.0", - "bunyan": "^1.1.3", - "supertest": "^0.14.0", - "tape": "^3.0.0" + "body-parser": "^1.18.3", + "bunyan": "^1.8.12", + "supertest": "^3.1.0", + "tape": "^4.9.1" }, "repository": { "type": "git", diff --git a/test.js b/test.js index b2be554..009f0be 100644 --- a/test.js +++ b/test.js @@ -59,7 +59,7 @@ test('request, response', function(t) { 'user-agent': userAgent, 'connection': 'close' }, - remoteAddress: /^v0\.11/.test(process.version) ? '::ffff:127.0.0.1' : '127.0.0.1', + remoteAddress: '::ffff:127.0.0.1', remotePort: requestLog.req.remotePort }, 'request log have the right `req` property'); });