-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
61 lines (58 loc) · 2.11 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
var Stream = require('stream');
var formatDate = require('./format_date');
module.exports = function(handle) {
handle('response', { affinity: 'sink' }, function(env, next) {
if (env.request) {
var req = env.request;
var res = env.response || env.target.response;
var UNKNOWN = '-';
var ip = req.connection.remoteAddress;
var date = '[' + formatDate(new Date()) + ']';
var method = req.method;
var url = req.url;
var requestSummary = '"' + method + ' ' + url + '"';
var status = res.statusCode;
var length = 0;
if( env.response.body !== null && env.response.body !== undefined) {
var body = res.body;
if(typeof body === 'string') {
var buf = new Buffer(body);
length = buf.length;
} else if (body instanceof Stream) {
length = UNKNOWN;
} else if (body instanceof Buffer) {
length = body.length;
} else if (typeof body === 'object') {
var bodyString = JSON.stringify(body);
var buf = new Buffer(bodyString);
length = buf.length;
}
var log = [ ip, UNKNOWN, UNKNOWN, date, requestSummary, status, length ];
console.log(log.join('\t'));
next(env);
} else {
var contentLength = env.response.getHeader('Content-Length');
if (contentLength == '0') {
length = 0;
var log = [ ip, UNKNOWN, UNKNOWN, date, requestSummary, status, length ];
console.log(log.join('\t'));
next(env);
} else if (env.target.response !== null && env.target.response !== undefined) {
env.target.response.getBody(function(err, body) {
if(body) {
length = body.length;
var log = [ ip, UNKNOWN, UNKNOWN, date, requestSummary, status, length ];
console.log(log.join('\t'));
next(env);
}
});
} else {
length = 0;
var log = [ ip, UNKNOWN, UNKNOWN, date, requestSummary, status, length ];
console.log(log.join('\t'));
next(env);
}
}
}
});
};