node-gamedig/lib/Logger.js

43 lines
1.1 KiB
JavaScript
Raw Normal View History

2019-01-20 10:45:57 +01:00
const HexUtil = require('./HexUtil');
class Logger {
constructor() {
this.debugEnabled = false;
}
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) {
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;