sync/src/logger.js

87 lines
2.2 KiB
JavaScript
Raw Normal View History

var fs = require("fs");
var path = require("path");
2017-07-09 03:11:54 +00:00
import { Logger as JsliLogger, LogLevel } from '@calzoneman/jsli';
import jsli from '@calzoneman/jsli';
2013-03-27 19:28:51 +00:00
function getTimeString() {
2013-05-04 16:43:38 +00:00
var d = new Date();
return d.toDateString() + " " + d.toTimeString().split(" ")[0];
2013-03-27 19:28:51 +00:00
}
var Logger = function(filename) {
this.filename = filename;
this.writer = fs.createWriteStream(filename, {
flags: "a",
encoding: "utf-8"
});
2018-04-07 22:30:30 +00:00
};
2013-03-27 19:28:51 +00:00
Logger.prototype.log = function () {
2013-07-29 23:32:51 +00:00
var msg = "";
for(var i in arguments)
msg += arguments[i];
if(this.dead) {
return;
}
2013-07-29 23:32:51 +00:00
var str = "[" + getTimeString() + "] " + msg + "\n";
try {
this.writer.write(str);
} catch(e) {
errlog.log("WARNING: Attempted logwrite failed: " + this.filename);
errlog.log("Message was: " + msg);
errlog.log(e);
}
2018-04-07 22:30:30 +00:00
};
2013-03-27 19:28:51 +00:00
Logger.prototype.close = function () {
try {
this.writer.end();
} catch(e) {
errlog.log("Log close failed: " + this.filename);
2013-07-29 22:16:11 +00:00
}
2018-04-07 22:30:30 +00:00
};
2013-03-27 19:28:51 +00:00
2014-01-28 00:37:48 +00:00
function makeConsoleLogger(filename) {
2018-04-07 22:30:30 +00:00
/* eslint no-console: off */
2014-01-28 00:37:48 +00:00
var log = new Logger(filename);
log._log = log.log;
log.log = function () {
console.log.apply(console, arguments);
this._log.apply(this, arguments);
2018-04-07 22:30:30 +00:00
};
2014-01-28 00:37:48 +00:00
return log;
}
var errlog = makeConsoleLogger(path.join(__dirname, "..", "error.log"));
var syslog = makeConsoleLogger(path.join(__dirname, "..", "sys.log"));
var eventlog = makeConsoleLogger(path.join(__dirname, "..", "events.log"));
2013-03-27 19:28:51 +00:00
exports.Logger = Logger;
exports.errlog = errlog;
exports.syslog = syslog;
2014-02-01 19:03:08 +00:00
exports.eventlog = eventlog;
2017-04-05 06:02:31 +00:00
class LegacyLogger extends JsliLogger {
2018-08-28 04:48:13 +00:00
constructor(loggerName, level) {
2017-07-09 03:11:54 +00:00
super(loggerName, level);
2017-04-05 06:02:31 +00:00
}
2018-08-28 04:48:13 +00:00
emitMessage(level, message) {
var output = `[${level.name}] ${this.loggerName}: ${message}`;
2017-04-05 06:02:31 +00:00
if (level.shouldLogAtLevel(LogLevel.ERROR)) {
2017-07-09 03:11:54 +00:00
errlog.log(output);
2017-04-05 06:02:31 +00:00
} else {
2017-07-09 03:11:54 +00:00
syslog.log(output);
2017-04-05 06:02:31 +00:00
}
}
}
2018-04-07 22:30:30 +00:00
// TODO: allow reconfiguration of log level at runtime
2018-08-28 04:48:13 +00:00
const level = process.env.DEBUG ? LogLevel.DEBUG : LogLevel.INFO;
2017-04-05 06:02:31 +00:00
2017-07-09 03:11:54 +00:00
jsli.setLogBackend((loggerName) => {
return new LegacyLogger(loggerName, level);
2017-04-05 06:02:31 +00:00
});