forked from tellnes/bunyan-middleware
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
35 lines (27 loc) · 883 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
var uuid = require('uuid');
module.exports = function logRequest(options) {
var logger = options.logger;
var headerName = options.headerName || 'x-request-id';
var serializers = options.serializers || logger.constructor.stdSerializers;
return function (req, res, next) {
var id = req.headers[headerName] || uuid.v4();
var now = Date.now();
var startOpts = {req: req};
req.log = logger.child({
type: 'request',
id: id,
serializers: serializers
});
if (req.body) {
startOpts.body = req.body;
}
res.setHeader(headerName, id);
req.log.info(startOpts, 'start request');
var 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');
});
next();
};
};