1 | module.exports = function(req, res, next) {
|
2 |
|
3 | req._startTime = new Date
|
4 |
|
5 | let originalWrite = res.write
|
6 | let originalEnd = res.end
|
7 |
|
8 | let chunks = []
|
9 |
|
10 | res.on('finish', function() {
|
11 |
|
12 | let log = {
|
13 | res: { statusCode: res.statusCode },
|
14 | req: {
|
15 | url: req.url,
|
16 | headers: req.headers,
|
17 | method: req.method,
|
18 | httpVersion: req.httpVersion,
|
19 | originUrl: req.originalUrl,
|
20 | body: req.body,
|
21 | query: req.params
|
22 | },
|
23 | responseTime: new Date - req._startTime,
|
24 | level: "info",
|
25 | message: `${req.method} ${req.url} HTTP/${req.httpVersion}`,
|
26 | timestamp: + req._startTime
|
27 | }
|
28 |
|
29 | if (res.statusCode >= 400) {
|
30 | log.res.error = res.body
|
31 | }
|
32 |
|
33 | Logger.log('api', 'trace', log)
|
34 |
|
35 | })
|
36 |
|
37 |
|
38 | res.write = function(chunk) {
|
39 |
|
40 | chunks.push(chunk)
|
41 |
|
42 | originalWrite.apply(res, arguments)
|
43 |
|
44 | }
|
45 |
|
46 | res.end = function(chunk) {
|
47 |
|
48 | if (chunk) { chunks.push(chunk) }
|
49 |
|
50 | res.body = chunks.toString('utf8')
|
51 |
|
52 | originalEnd.apply(res, arguments)
|
53 |
|
54 | }
|
55 |
|
56 | res.on('close', function() {
|
57 |
|
58 |
|
59 |
|
60 | })
|
61 |
|
62 | return next()
|
63 |
|
64 | }
|