This repository has been archived by the owner on Dec 18, 2019. It is now read-only.
forked from bahamas10/node-access-log
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
72 lines (60 loc) · 2.17 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
61
62
63
64
65
66
67
68
69
70
71
72
var strftime = require('strftime');
var defaultformat = ':ip - :userID [:clfDate] ":method :url HTTP/:httpVersion" :statusCode :contentLength ":referer" ":userAgent"';
module.exports = accesslog;
function accesslog(req, res, format, cb) {
if (typeof format === 'function') {
cb = format;
format = null;
}
format = format || defaultformat;
cb = cb || console.log.bind(console);
var uriDecoded = req.url;
try {
uriDecoded = decodeURIComponent(uriDecoded);
} catch (e) {}
var start = new Date();
// override res.writeHead to track contentLength
var resWriteHead = res.writeHead.bind(res);
res.writeHead = function(statusCode, reason, headers) {
resWriteHead.apply(res, arguments);
if (typeof reason === "object" && !headers) {
headers = reason;
reason = null;
}
if (headers) {
for (var k in headers) {
if (k.toLowerCase() == "content-length") {
res.contentLength = headers[k];
}
}
}
};
// override res.end to capture all responses
var resend = res.end.bind(res);
res.end = function() {
// call the original
resend.apply(res, arguments);
var end = new Date();
var delta = end - start;
var s = format
.replace(':clfDate', strftime('%d/%b/%Y:%H:%M:%S %z', end))
.replace(':contentLength', res.getHeader('content-length') || res.contentLength || '-')
.replace(':delta', delta)
.replace(':endDate', end.toISOString())
.replace(':endTime', end.getTime())
.replace(':httpVersion', req.httpVersion)
.replace(':ip', req.headers['x-forwarded-for'] || req.connection.remoteAddress || '-')
.replace(':method', req.method)
.replace(':protocol', req.connection.encrypted ? 'HTTPS' : 'HTTP')
.replace(':referer', req.headers['referer'] || '-')
.replace(':startDate', start.toISOString())
.replace(':startTime', start.getTime())
.replace(':statusCode', res.statusCode)
.replace(':url', req.url)
.replace(':urlDecoded', uriDecoded)
.replace(':userID', (req.session && (req.session.user || req.session.id)) || '-')
.replace(':userAgent', req.headers['user-agent'] || '-');
// log it
cb(s);
};
}