wottpal
4/18/2018 - 7:38 PM

A convenience wrapper around the Console API which adds several functionalities.

A convenience wrapper around the Console API which adds several functionalities.

/**
* A convenience wrapper around the Console API which adds:
*   - Logging has to be globally enabled first (in a dev-environment)
*   - Even when disabled logged messages are cached and can be displayed later
*   - Prefix messages with a custom〈 Label 〉
*
* TODO Maybe add verbose-flag to really be able to log everything if needed
**/


const debug = (() => {

  /* Variables */

  let shouldLog = false
  let cachedLog = []


  /* Private Functions */

  /**
  * This function outputs all cache-messages.
  */
  function outputCache() {
    if (!cachedLog || cachedLog.length <= 0) return

    console.group(`Cached Messages (${cachedLog.length})`)
    cachedLog.forEach(item => {
      debug.log(item.message, item.type, item.label)
    })
    console.groupEnd()
  }

  /**
  * This function determines if the given label can be a string prefix
  */
  function canPrefixLabel(message) {
    return ['number', 'boolean', 'string', 'undefined'].includes(typeof message)
  }


  /* Global Functions */

  return {

    /**
    * Enables logging and displays all cached messages while disabled.
    */
    'enable' : (enabled = true) => {
      shouldLog = enabled
      outputCache()
      cachedLog = []
    },

    /**
    * The actual logging function which can have a label and another type.
    * See the Console API for all available types: https://goo.gl/rNW81W
    */
    'log' : (message, type = 'log', label) => {
      // Cache message if logging is disabled
      if (!shouldLog) {
        cachedLog.push({ message: message, type: type, label: label})
        return;
      }

      // Prefix or print label on new line
      if (label && canPrefixLabel(message)) {
        message = `%c〈 ${label} 〉%c ${message}`
        console[type](message, "color:gray", "")

      } else {
        if (label) console.group(`%c〈 ${label} 〉${typeof message}`,  "color:gray;font-weight:normal")
        console[type](message)
        if (label) console.groupEnd()
      }
    },

    /**
    * Returns a logger which always has the given label.
    */
    'labeledLogger' : (label) => {
      return (message, type) => {
        log(message, type, label)
      }
    },

  }

})()


/**
* Global Shortcuts
*/

const log = debug.log
const labeledLogger = debug.labeledLogger