83 lines
2.8 KiB
JavaScript
Executable File
83 lines
2.8 KiB
JavaScript
Executable File
const moment = require('moment');
|
|
const colors = require('colors/safe');
|
|
const util = require('util');
|
|
|
|
function padCenter(x, p, n) {
|
|
x = '' + x;
|
|
let z = false;
|
|
while (x.length < n) {
|
|
if (z) {
|
|
z = false;
|
|
x = p + x;
|
|
} else {
|
|
z = true;
|
|
x = x + p;
|
|
}
|
|
}
|
|
return x;
|
|
}
|
|
|
|
function createLogger(name, processConsole) {
|
|
processConsole = processConsole || console;
|
|
let logger = {};
|
|
function colorize(level, text) {
|
|
let map = {
|
|
'error': colors.red,
|
|
'warn': colors.yellow,
|
|
'info': colors.green,
|
|
'debug': colors.blue,
|
|
'silly': colors.magenta,
|
|
};
|
|
if (level in map) {
|
|
return map[level](text);
|
|
} else {
|
|
return colors.bgWhite(text);
|
|
}
|
|
}
|
|
logger.log = function(level, message, data) {
|
|
let prefix = `[ ${colorize(level, padCenter(level, ' ', 5))} | ${padCenter(name, ' ', 6)} | ${moment().format('HH:mm:ss.SSS')} ]`;
|
|
let out = '';
|
|
if (message !== undefined && typeof message !== 'string') {
|
|
data = message;
|
|
message = null;
|
|
}
|
|
if (message) {
|
|
out += message.split('\n').map(o => `${prefix}: ${o}`).join('\n');
|
|
// out += `${prefix}: ${message}`;
|
|
}
|
|
function handleData(data) {
|
|
if (data) {
|
|
if (typeof message === 'string') {
|
|
out += '\n';
|
|
}
|
|
if (data instanceof Error) {
|
|
if (data.stack) {
|
|
out += `${prefix}# ${data.stack.split('\n').join(`\n${prefix}# `)}`;
|
|
} else {
|
|
out += `${prefix}# ${data.name}: ${data.message}`;
|
|
}
|
|
} else {
|
|
let s = util.inspect(data, { colors: true });
|
|
s = s.split('\n').map(o => `${prefix}$ ${o}`).join('\n');
|
|
out += s;
|
|
//let s = `{${prettyjson.render(data).split('\n').map(o => ' ' + o).join('\n').substring(1)} }`;
|
|
//out += `${prefix}$ ${s.split('\n').map(o => colors.italic(o)).join(`\n${prefix}$ `)}`;
|
|
}
|
|
}
|
|
}
|
|
if (Array.isArray(data)) {
|
|
data.forEach(handleData);
|
|
} else {
|
|
handleData(data);
|
|
}
|
|
processConsole.log(out);
|
|
}
|
|
logger.error = (message, data) => { logger.log('error', message, data); };
|
|
logger.warn = (message, data) => { logger.log('warn', message, data); };
|
|
logger.info = (message, data) => { logger.log('info', message, data); };
|
|
logger.debug = (message, data) => { logger.log('debug', message, data); };
|
|
logger.silly = (message, data) => { logger.log('silly', message, data); };
|
|
return logger;
|
|
}
|
|
|
|
module.exports = createLogger; |