logger.js 1.12 KB
Newer Older
1 2
const chalk = require('chalk')
const EventEmitter = require('events')
3

4
/* global WIKI */
5

6 7 8 9 10 11 12 13 14 15 16 17 18
const LEVELS = ['error', 'warn', 'info', 'debug']
const LEVELSIGNORED = ['verbose', 'silly']
const LEVELCOLORS = {
  error: 'red',
  warn: 'yellow',
  info: 'green',
  debug: 'cyan'
}

class Logger extends EventEmitter {}
const primaryLogger = new Logger()

let ignoreNextLevels = false
19

20 21 22 23
LEVELS.forEach(lvl => {
  primaryLogger[lvl] = (...args) => {
    primaryLogger.emit(lvl, ...args)
  }
24

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
  if (!ignoreNextLevels) {
    primaryLogger.on(lvl, (msg) => {
      if (WIKI.config.logFormat === 'json') {
        console.log(JSON.stringify({
          timestamp: new Date().toISOString(),
          instance: WIKI.INSTANCE_ID,
          level: lvl,
          message: msg
        }))
      } else {
        console.log(chalk`${new Date().toISOString()} {dim [${WIKI.INSTANCE_ID}]} {${LEVELCOLORS[lvl]}.bold ${lvl}}: ${msg}`)
      }
    })
  }
  if (lvl === WIKI.config.logLevel) {
    ignoreNextLevels = true
  }
})
43

44 45 46
LEVELSIGNORED.forEach(lvl => {
  primaryLogger[lvl] = () => {}
})
47

48 49 50 51
module.exports = {
  loggers: {},
  init () {
    return primaryLogger
52
  }
53
}