-
Notifications
You must be signed in to change notification settings - Fork 18
/
logs_highcharts.js
103 lines (90 loc) · 2.51 KB
/
logs_highcharts.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
var fs = require("fs");
var _ = require("underscore");
var utils = require("./public/js/shared_utils.js");
var UPDATE_FROM_LOGS_FREQUENCY = 1000 * 60 * 60 * 24;
var USAGE_HISTOGRAM_DAYS = 10;
// TODO: repetition of code here with the types
var FACT_TYPES = ["trivia", "math", "year", "date"];
var typeTimeHistogram = {};
var typeNumberHistogram = {};
function updateStatsFromLogs() {
// Clear the histogram first
_.each(FACT_TYPES, function (key) {
typeTimeHistogram[key] = {};
typeNumberHistogram[key] = {};
});
fs.readdir("./logs", function (err, files) {
_.each(files, function (file) {
fs.readFile("./logs/" + file, "utf-8", function (err, contents) {
_.each(contents.split("\n"), function (logJson) {
var logObj = null;
try {
logObj = JSON.parse(logJson);
} catch (e) {}
if (logObj) {
try {
reduceStats(logObj);
} catch (e) {
console.log("Failed reducing log file", file);
console.log(e.message, e.stack);
}
}
});
});
});
});
}
function reduceStats(obj) {
var timestamp = obj.time;
var query = obj.query;
var number = query.num || "random";
if (query.month && query.day) {
number = utils.monthDayToDayOfYear(query.month, query.day);
}
var type = query.type || "trivia";
// There may be invalid types due to invalid user input
if (!_.contains(FACT_TYPES, type)) return;
// by time
if (
timestamp >=
new Date().getTime() - 1000 * 60 * 60 * 24 * USAGE_HISTOGRAM_DAYS
) {
var date = new Date(timestamp);
var flooredDate = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate()
);
var flooredTime = flooredDate.getTime();
var hist = typeTimeHistogram[type];
if (!hist[flooredTime]) {
hist[flooredTime] = 0;
}
hist[flooredTime] += 1;
}
// By number
hist = typeNumberHistogram[type];
if (!hist[number]) {
hist[number] = 0;
}
hist[number] += 1;
}
updateStatsFromLogs();
setInterval(updateStatsFromLogs, UPDATE_FROM_LOGS_FREQUENCY);
function toHighchartsData(histogram, intKey) {
var ret = {};
_.each(histogram, function (hist, type) {
ret[type] = _.map(hist, function (value, key) {
if (intKey) key = +key;
return [key, value];
});
});
return ret;
}
exports.getTypeTimeHist = _.bind(
toHighchartsData,
null,
typeTimeHistogram,
true
);
exports.getTypeNumberHist = _.bind(toHighchartsData, null, typeNumberHistogram);