forked from vvo/bunyan-request
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
54 lines (40 loc) · 1.08 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const uuid = require('uuid');
module.exports = function logRequest({headerName='x-request-id', logger}={}) {
return function (req, res, next) {
const id = req.headers[headerName] || uuid.v4();
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);
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() {
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();
};
};