keeweb/app/scripts/util/logger.js

87 lines
2.0 KiB
JavaScript
Raw Normal View History

2015-12-12 09:53:50 +01:00
'use strict';
2016-04-09 14:55:27 +02:00
var Level = {
Off: 0,
Error: 1,
Warn: 2,
Info: 3,
Debug: 4,
All: 5
};
2016-06-04 10:31:06 +02:00
var MaxLogsToSave = 100;
var lastLogs = [];
2015-12-12 09:53:50 +01:00
var Logger = function(name, id) {
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];
2016-04-09 14:55:27 +02:00
if (this.level > Level.Debug) {
2016-06-04 10:31:06 +02:00
Logger.saveLast('debug', arguments);
2016-07-17 13:30:38 +02:00
console.debug.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];
2016-04-09 14:55:27 +02:00
if (this.level > Level.Info) {
2016-06-04 10:31:06 +02:00
Logger.saveLast('info', arguments);
2016-07-17 13:30:38 +02:00
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.warn = function() {
arguments[0] = this.getPrefix() + arguments[0];
2016-04-09 14:55:27 +02: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];
2016-04-09 14:55:27 +02: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;