This repository has been archived by the owner on Feb 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch-logs.js
143 lines (120 loc) · 4.8 KB
/
watch-logs.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
'use strict';
const args = require('yargs').argv;
const fs = require('fs');
const filePath = args.path || '/tmp/access.log';
const time = args.time || 10000;
const sectionsLimit = args.limit || 5;
const seconds = time / 1000;
let currentPosition = 0;
try {
if (fs.existsSync(filePath)) {
fs.stat(filePath, {}, function (err, stats) {
if (err) throw err;
currentPosition = stats.size;
console.log(`Waiting ${seconds} seconds before starting`);
setTimeout(processLogs, time);
})
} else {
console.error(`There is no file existing at provided path ${filePath}`);
}
} catch (err) {
console.error(err);
}
// open file
// set position to last line
// read file during 10 seconds
// after these 10 seconds, close file
// and do it again
function processLogs() {
const start = new Date();
const end = new Date(start.getTime() + time);
let logs = {};
let visitorsIP = [];
const stream = fs.createReadStream(filePath, {
encoding: 'utf-8',
flags: 'r',
start: currentPosition
});
stream
.on('data', function (chunk) {
currentPosition += chunk.length;
const lines = chunk.toString().split("\n");
if (lines) {
lines.forEach(function (line) {
if (line !== '') {
const result = line.match(/^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+)\s?(\S+)?\s?(\S+)?" (\d{3}|-) (\d+|-)\s?"?([^"]*)"?\s?"?([^"]*)?"?$/);
if (result) {
let ip = result[1];
if (visitorsIP.indexOf(ip) === -1) {
visitorsIP.push(ip);
}
let urlParts = result[6].split('/');
const section = urlParts[1];
const code = result[8];
// check if section has already been created
if (typeof logs[section] === 'undefined') {
logs[section] = {
visits: 0
};
}
logs[section].visits += 1;
if (typeof logs[section].codes === 'undefined') {
logs[section].codes = {};
}
if (typeof logs[section].codes[code] === 'undefined') {
logs[section].codes[code] = 0;
}
logs[section].codes[code] += 1;
} else {
console.warn('Skipping wrongly formatted line: ', line);
}
}
})
}
})
.on('close', function () {
let sortable = [];
for (const [key, value] of Object.entries(logs)) {
sortable.push([key, value.visits]);
}
sortable.sort(function (a, b) {
return b[1] - a[1];
});
if (sectionsLimit) {
sortable = sortable.slice(0, sectionsLimit - 1);
}
const stats = {};
sortable.forEach(function (item) {
// calculate error rates
let errorRate = 0;
let redirectionRate = 0;
let total = logs[item[0]].visits;
let errors = 0;
let redirections = 0;
for (const [code, number] of Object.entries(logs[item[0]].codes)) {
if (code.substr(0, 1) === '4' || code.substr(0, 1) === '5') {
errors += number;
} else if (code.substr(0, 1) === '3') {
redirections += number;
}
}
errorRate = (errors / total) * 100;
redirectionRate = (redirections / total) * 100;
errorRate = errorRate.toFixed(2) + '%';
redirectionRate = redirectionRate.toFixed(2) + '%';
stats[item[0]] = {
visits: item[1],
error_rates: errorRate,
redirection_rates: redirectionRate
}
});
if (stats) {
console.info(`Most visited sections from ${start.toLocaleTimeString()} to ${end.toLocaleTimeString()} for log file ${filePath} (last ${seconds} seconds)`);
console.table(stats);
console.info(`${visitorsIP.length} total unique visits`);
} else {
console.info('No visits, no stats to display');
}
})
setTimeout(processLogs, time);
}