-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsuperagent-logger.js
95 lines (82 loc) · 2.51 KB
/
superagent-logger.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
'use strict';
var url = require('url');
var querystring = require('qs');
var chalk = require('chalk');
var superagent = require('superagent');
exports = module.exports = function(options) {
if(!options) options = {};
if(options instanceof superagent.Request)
return attachSuperagentLogger({}, options);
return attachSuperagentLogger.bind(null, options);
};
function attachSuperagentLogger(options, req) {
var start = new Date().getTime();
var timestamp = new Date().toISOString();
var uri = url.parse(req.url);
var method = req.method;
if(options.outgoing) {
var qslog = '';
if (req.qs) {
qslog = '?' + querystring.stringify(req.qs);
}
console.log('%s %s %s %s %s %s',
chalk.gray(
rightPad(uri.protocol.toUpperCase().replace(/[^\w]/g, ''), 5)
),
chalk.gray(rightPad(method.toUpperCase(), 'delete'.length)),
options.timestamp ? chalk.gray('[' + timestamp + ']') : '',
chalk.gray(' - '),
chalk.gray(uri.href + qslog),
chalk.gray(req._data ? JSON.stringify(req._data) : '')
);
}
req.on('response', function(res) {
var now = new Date().getTime();
var elapsed = now - start;
var st = res.status;
if(st < 300) {
st = chalk.green(st);
} else if (st < 400) {
st = chalk.yellow(st);
} else {
st = chalk.red(st);
}
var qslog = '';
if (req.qs) {
qslog = '?' + querystring.stringify(req.qs);
}
console.log('%s %s %s %s %s %s %s',
chalk.magenta(
rightPad(uri.protocol.toUpperCase().replace(/[^\w]/g, ''), 5)
),
chalk.cyan(rightPad(method.toUpperCase(), 'delete'.length)),
options.timestamp ? chalk.gray('[' + timestamp + ']') : '',
st,
chalk.gray(uri.href + qslog),
chalk.gray('(') +
chalk[colorForSpeed(elapsed)](elapsed + 'ms') +
chalk.gray(')'),
chalk.gray(res.text)
);
});
}
function colorForSpeed(ms) {
if(ms < 200) {
return 'green';
} else if(ms < 1000) {
return 'gray';
} else if(ms < 5000) {
return 'yellow';
} else {
return 'red';
}
}
function rightPad(str, len) {
var l = str.length;
if(l < len) {
for(var i = 0, n = len - l; i < n; i++) {
str += ' ';
}
}
return str;
}