How to take control of JavaScript console output

Published: | Updated: | by Julian Knight Reading time ~1 min.
📖 Kb | 📎 Development | 🔖 javascript, ecmascript

All browsers have the console object that lets you output to the developer console log. But in production, you don’t want this output, only in development. So here is the easiest way I’ve found to take control.

This is a simple example and really needs expanding to be more general purpose.

It uses a global debug variable to control output. If debug is false, no output will occur.

All functions of the console object are taken over by this function.

Code 🔗︎

/** Debugging function
 * @param {string} type One of log|error|warn|info|dir, etc
 * @param {...*} msg Msg(s) to send to console
 * WARNING: ...args is ES6, it doesn't work on IE11
 * @since 2019-02-01 Apply any number of args
 **/
//myDebug = function (type, ...args) {
myDebug = function () {
    if (!debug) return

    var type = arguments[0]

    //console[type](...args)
    console[type].apply(undefined, [].slice.call(arguments, 1))

} // --- End of debug function --- //

comments powered by Disqus