All files / src get-logger.js

100% Statements 15/15
100% Branches 14/14
100% Functions 9/9
100% Lines 15/15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64          18x                     7x             21x 6x 4x 4x             4x 1x         6x   3x         1x               54x 6x 6x         18x    
import console from 'console'
import arrify from 'arrify'
import {oneLineTrim} from 'common-tags'
import {isPlainObject, includes} from 'lodash'
 
const shouldLog = {
  // fn called         logLevels
  info: getShouldLogFn('', 'debug', 'info'),
  warn: getShouldLogFn('', 'debug', 'info', 'warn'),
  error: getShouldLogFn('', 'debug', 'info', 'warn', 'error'),
}
 
export default getLogger
export {getLogLevel}
 
function getLogger(logLevel) {
  return {
    error: getLogFn('error'),
    warn: getLogFn('warn'),
    info: getLogFn('info'),
  }
 
  function getLogFn(name) {
    return function logFn(...args) {
      if (shouldLog[name](process.env.LOG_LEVEL || logLevel)) {
        const message = getMessage(...args)
        console[name](...message) // eslint-disable-line no-console
      }
    }
  }
}
 
function getMessage(first, ...rest) {
  if (isPlainObject(first) && first.message && first.ref) {
    return [
      ...arrify(first.message),
      getLink(first.ref),
      first.error,
      ...rest,
    ].filter(i => !!i)
  } else {
    return [first, ...rest]
  }
}
 
function getLink(ref) {
  return oneLineTrim`
    https://github.com/sezna/nps/blob/master
    /other/ERRORS_AND_WARNINGS.md#
    ${ref}
  `
}
 
function getShouldLogFn(...acceptableValues) {
  return function shouldLogWithLevel(logLevel = '') {
    logLevel = logLevel.toLowerCase()
    return !logLevel || includes(acceptableValues, logLevel)
  }
}
 
function getLogLevel({silent, logLevel}) {
  return silent ? 'disable' : logLevel
}