-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
58 lines (49 loc) · 1.36 KB
/
middleware.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
55
56
57
58
const bufflog = require('@bufferapp/bufflog');
const onFinished = require('on-finished');
const { getRequestDataToLog } = require('./lib/utils');
/**
* middleware
* Logging middleware which logs to stdout always to a file in production
*
* @param {Object.<String>}
* @return {Function}
*/
module.exports = function middleware(options) {
const {
getMetadata,
getStats,
params,
} = options;
return function logRequest(req, res, next) {
const startTime = new Date();
const request = getRequestDataToLog(req, params);
onFinished(res, () => {
const finishTime = new Date();
const timestamp = finishTime.toJSON();
const responseTime = finishTime.getTime() - startTime.getTime();
const response = {
statusCode: res.statusCode,
responseTime,
};
if (req.errorLog) {
response.error = req.errorLog;
}
const metadata = getMetadata ? getMetadata(req) : {};
const stats = getStats ? getStats(req, responseTime) : {};
const msg = `${req.method} ${request.url} ${res.statusCode} - ${responseTime}ms`;
const info = {
timestamp,
request,
response,
metadata,
stats,
};
if (response.error) {
bufflog.error(response.error, info);
} else {
bufflog.info(msg, info);
}
});
next();
};
};