-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
46 lines (37 loc) · 1.29 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
var url = require('url')
exports.create = function(logger, options) {
return function(req, res, next) {
var rEnd = res.end;
// To track response time
req._rlStartTime = new Date();
// Setup the key-value object of data to log and include some basic info
req.kvLog = {
date: req._rlStartTime.toISOString()
, method: req.method
, url: url.parse(req.originalUrl).pathname
, _rlLevel: 'info' // internal usage
, type: 'reqlog'
};
// Proxy the real end function
res.end = function(chunk, encoding) {
// Do the work expected
res.end = rEnd;
res.end(chunk, encoding);
// And do the work we want now (logging!)
// Conditionally do so if url matches a specific exclude.
if (options && options.excludes && options.excludes.indexOf(req.kvLog.url) > -1) return;
// Save a few more variables that we can only get at the end
req.kvLog.status = res.statusCode;
req.kvLog.response_time = (new Date() - req._rlStartTime);
// Send the log off to winston
var level = req.kvLog._rlLevel
, msg = req.kvLog.message || '';
delete req.kvLog._rlLevel;
if (msg.length) {
delete req.kvLog.message;
}
logger.log(level, msg, req.kvLog);
};
next();
};
};