keeweb/app/scripts/util/logger.js

85 lines
2.0 KiB
JavaScript
Raw Normal View History

2017-01-31 07:50:28 +01:00
const Level = {
2016-04-09 14:55:27 +02:00
Off: 0,
Error: 1,
Warn: 2,
Info: 3,
Debug: 4,
All: 5
};
2017-01-31 07:50:28 +01:00
const MaxLogsToSave = 100;
2016-06-04 10:31:06 +02:00
2017-01-31 07:50:28 +01:00
const lastLogs = [];
2016-06-04 10:31:06 +02:00
2017-01-31 07:50:28 +01:00
const Logger = function(name, id) {
2019-08-16 23:05:39 +02:00
this.prefix = name ? name + (id ? ':' + id : '') : 'default';
2016-04-09 14:55:27 +02:00
this.level = Level.All;
2015-12-12 09:53:50 +01:00
};
Logger.prototype.ts = function(ts) {
if (ts) {
return Math.round(performance.now() - ts) + 'ms';
} else {
return performance.now();
}
};
Logger.prototype.getPrefix = function() {
return new Date().toISOString() + ' [' + this.prefix + '] ';
};
Logger.prototype.debug = function() {
arguments[0] = this.getPrefix() + arguments[0];
2018-03-24 21:17:20 +01:00
if (this.level >= Level.Debug) {
2016-06-04 10:31:06 +02:00
Logger.saveLast('debug', arguments);
console.log.apply(console, arguments); // eslint-disable-line no-console
2016-04-09 14:55:27 +02:00
}
2015-12-12 09:53:50 +01:00
};
Logger.prototype.info = function() {
arguments[0] = this.getPrefix() + arguments[0];
2018-03-24 21:17:20 +01:00
if (this.level >= Level.Info) {
2016-06-04 10:31:06 +02:00
Logger.saveLast('info', arguments);
console.info.apply(console, arguments); // eslint-disable-line no-console
2016-04-09 14:55:27 +02:00
}
2015-12-12 09:53:50 +01:00
};
Logger.prototype.warn = function() {
arguments[0] = this.getPrefix() + arguments[0];
2018-03-24 21:17:20 +01:00
if (this.level >= Level.Warn) {
2016-06-04 10:31:06 +02:00
Logger.saveLast('warn', arguments);
2016-07-17 13:30:38 +02:00
console.warn.apply(console, arguments); // eslint-disable-line no-console
2016-04-09 14:55:27 +02:00
}
2015-12-12 09:53:50 +01:00
};
Logger.prototype.error = function() {
arguments[0] = this.getPrefix() + arguments[0];
2018-03-24 21:17:20 +01:00
if (this.level >= Level.Error) {
2016-06-04 10:31:06 +02:00
Logger.saveLast('error', arguments);
2016-07-17 13:30:38 +02:00
console.error.apply(console, arguments); // eslint-disable-line no-console
2016-04-09 14:55:27 +02:00
}
2015-12-12 09:53:50 +01:00
};
2016-04-09 14:55:27 +02:00
Logger.prototype.setLevel = function(level) {
this.level = level;
};
Logger.prototype.getLevel = function() {
return this.level;
};
2016-06-04 10:31:06 +02:00
Logger.saveLast = function(level, args) {
lastLogs.push({ level: level, args: Array.prototype.slice.call(args) });
if (lastLogs.length > MaxLogsToSave) {
lastLogs.shift();
}
};
Logger.getLast = function() {
return lastLogs;
};
2016-04-09 14:55:27 +02:00
Logger.Level = Level;
2015-12-12 09:53:50 +01:00
module.exports = Logger;