javascript Console API的便利包装,增加了几个功能。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Console API的便利包装,增加了几个功能。相关的知识,希望对你有一定的参考价值。

/**
* 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

以上是关于javascript Console API的便利包装,增加了几个功能。的主要内容,如果未能解决你的问题,请参考以下文章

在 Javascript 中调用 console.log() 后的空控制台

JavaScript数组常用API方法汇总

JavaScript 中 this的指向

JavaScript常用API合集汇总

如何将javascript变量或console.log(变量)保存到文件中

JavaScript常用API合集汇总