ice.fo.utils
Version:
137 lines (111 loc) • 3.12 kB
JavaScript
const useLogger = (function () {
try {
return require('winston').version.split('.')[0] >= 3
} catch (er) {
return false
}
})()
const logLevels = {
trace: 0,
error: 1,
warn: 2,
info: 3,
http: 4,
verbose: 5,
debug: 6,
silly: 7,
}
const consoleFgColors = {
FgGreen: '\x1B[32m',
FgWhite: '\x1B[37m',
FgYellow: '\x1B[33m',
}
const consoleBgColors = {
BgRed: '\x1B[41m',
BgBlue: '\x1B[44m',
}
const DummyLogger = {
console () {
},
info () {
},
error () {
},
}
function buildConsoleColorForText (text, color) {
return `${color}${text}\x1B[0m`
}
module.exports = function ({ $config }) {
if (!useLogger) {
return DummyLogger
}
const loggerConfig = $config.logger || {}
const useConsoleLog = !!loggerConfig.console
const ServerLogger = {
...DummyLogger,
logger: (function () {
const winston = require('winston')
return winston.createLogger({
levels: logLevels,
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json(),
),
defaultMeta: { },
transports: [
new winston.transports.Console({
level: 0,
format: winston.format.printf((info) => {
return info.message + '\n'
}),
}),
],
})
})(),
console: !useConsoleLog
? () => {}
: function (...args) {
const groupLabel = buildConsoleColorForText(buildConsoleColorForText(' CONSOLE ', consoleBgColors.BgBlue), consoleFgColors.FgWhite)
const minLines = 2
for (let i = 0; i < minLines - args.length; i++) {
args.push('')
}
const messages = args.map((i, index) => {
if (index == 0 && typeof i == 'string' && args.length > 1) {
return buildConsoleColorForText(i, consoleFgColors.FgGreen)
}
switch (typeof i) {
case 'object':
return Object.entries(i).map(([k, v]) => {
return buildConsoleColorForText(k, consoleFgColors.FgYellow) + ' ' + v
}).join('\n ')
default:
return i
}
})
this.logger.log('error', groupLabel + '\n ' + messages.join('\n '))
},
info () {
},
error (...args) {
const groupLabel = buildConsoleColorForText(buildConsoleColorForText(' ERROR ', consoleBgColors.BgRed), consoleFgColors.FgWhite)
const messages = args.map((i, index) => {
if (index == 0 && typeof i == 'string') {
return buildConsoleColorForText(i, consoleFgColors.FgGreen)
}
switch (typeof i) {
case 'object':
if (i.message) {
return i.message
}
return Object.entries(i).map(([k, v]) => buildConsoleColorForText(k, consoleFgColors.FgYellow) + ' ' + v).join(' ')
default:
return i
}
})
this.logger.log('error', groupLabel + '\n ' + messages.join('\n '))
},
}
return ServerLogger
}