CyTube/actionlog.js

66 lines
1.6 KiB
JavaScript
Raw Normal View History

2013-06-22 01:28:21 +00:00
var fs = require("fs");
2013-06-23 18:02:20 +00:00
var Logger = require("./logger");
2013-06-22 01:28:21 +00:00
var buffer = [];
2013-06-23 18:02:20 +00:00
exports.record = function(ip, name, action, args) {
2013-06-22 01:28:21 +00:00
buffer.push(JSON.stringify({
ip: ip,
name: name,
action: action,
2013-06-23 18:02:20 +00:00
args: args ? args : [],
2013-06-22 01:28:21 +00:00
time: Date.now()
}));
}
exports.flush = function() {
if(buffer.length == 0)
return;
var text = buffer.join("\n") + "\n";
buffer = [];
fs.appendFile("action.log", text, function(err) {
if(err) {
errlog.log("Append to actionlog failed: ");
errlog.log(err);
}
});
}
2013-06-23 18:02:20 +00:00
exports.clear = function(actions) {
clearInterval(FLUSH_TMR);
var rs = fs.createReadStream("action.log");
var ws = fs.createWriteStream("action.log.tmp");
function handleLine(ln) {
try {
js = JSON.parse(ln);
if(actions.indexOf(js.action) == -1)
ws.write(ln + "\n");
}
catch(e) { }
}
var buffer = "";
rs.on("data", function(chunk) {
buffer += chunk;
if(buffer.indexOf("\n") != -1) {
var lines = buffer.split("\n");
buffer = lines[lines.length - 1];
lines.length = lines.length - 1;
lines.forEach(handleLine);
}
});
rs.on("end", function() {
handleLine(buffer);
ws.end();
});
2013-06-22 01:28:21 +00:00
try {
2013-06-23 18:02:20 +00:00
fs.renameSync("action.log.tmp", "action.log");
}
catch(e) {
Logger.errlog.log("Failed to move action.log.tmp => action.log");
Logger.errlog.log(e);
2013-06-22 01:28:21 +00:00
}
2013-06-23 18:02:20 +00:00
FLUSH_TMR = setInterval(exports.flush, 15000);
2013-06-22 01:28:21 +00:00
}
2013-06-23 18:02:20 +00:00
var FLUSH_TMR = setInterval(exports.flush, 15000);