node-gamedig/lib/Logger.js

47 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-01-20 10:45:57 +01:00
const HexUtil = require('./HexUtil');
class Logger {
constructor() {
this.debugEnabled = false;
2019-02-14 05:46:13 +01:00
this.prefix = '';
2019-01-20 10:45:57 +01:00
}
debug(...args) {
if (!this.debugEnabled) return;
this._print(...args);
}
_print(...args) {
try {
const strings = this._convertArgsToStrings(...args);
2019-01-20 11:21:40 +01:00
if (strings.length) {
2019-02-14 05:46:13 +01:00
if (this.prefix) {
strings.unshift(this.prefix);
}
2019-01-20 11:21:40 +01:00
console.log(...strings);
}
2019-01-20 10:45:57 +01:00
} catch(e) {
console.log("Error while logging: " + e);
}
}
_convertArgsToStrings(...args) {
const out = [];
for (const arg of args) {
if (arg instanceof Error) {
out.push(arg.stack);
} else if (arg instanceof Buffer) {
2019-01-20 11:21:40 +01:00
out.push(HexUtil.debugDump(arg));
2019-01-20 10:45:57 +01:00
} else if (typeof arg == 'function') {
2019-01-20 11:21:40 +01:00
const result = arg.call(undefined, (...args) => this._print(...args));
2019-01-20 10:45:57 +01:00
if (result !== undefined) out.push(...this._convertArgsToStrings(result));
} else {
out.push(arg);
}
}
return out;
}
}
module.exports = Logger;