requestLogger.js
1.3 KB
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
var moment = require('moment');
exports = module.exports = function (logger,settings) {
return function (req, res, next) {
var requestEnd = res.end
, requestedUrl = req.originalUrl
, startTime = new Date();
var level = 'error';
if(settings&&settings.output&&settings.output.level){
level=settings.output.level;
}
// Proxy the real end function
res.end = function (chunk, encoding) {
var data = {
'date': moment(startTime).format(),
'statusCode': res.statusCode,
'method': req.method,
'responseTime': (new Date() - startTime),
'deviceId':req.headers['device-id']||'',
'xRequestId':req.headers['x-request-id']||'',
'url': requestedUrl,
'ip': req.headers['client-ip'] || req.ip || req.connection.remoteAddress,
'userAgent': req.headers['user-agent']
};
// Do the work expected
res.end = requestEnd;
res.end(chunk, encoding);
if(res.statusCode>=400){//响应错误
logger.error(data);
}else if('debug'==level){
logger.debug(data);
}else{
logger.info(data);
}
};
next();
};
};