Conditional Logging

From GreaseSpot Wiki
Revision as of 02:26, 4 February 2010 by Arantius (talk | contribs) (Created page with 'Provide a single easy switch to control whether debugging information is output. == Alternative 1 == <pre class='sample'> const DEBUG = true; function debug() { if (DEBUG &&…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Provide a single easy switch to control whether debugging information is output.

Alternative 1

const DEBUG = true;

function debug() {
  if (DEBUG && console) {
    console.log.apply(this, arguments);
  }
}
var links = document.links;
debug("Links: %o", links);

Alternative 2

A slightly simpler method that lets you use more of the Firebug console's routines.

const DEBUG = 1;

var _orig_console = console;
var console = {
  log: function (text) { if (DEBUG) _orig_console.log(text); },
  info: function (text) { if (DEBUG) _orig_console.info(text); },
  warn: function (text) { if (DEBUG) _orig_console.warn(text); },
  error: function (text) { if (DEBUG) _orig_console.error(text); }
};

Alternative 3

An even simpler option, retaining all of Firebug's console routines, and not interfering with additional parameters.

const DEBUG = 1;
if (!DEBUG) {
  var console = {
    log: function() {},
    info: function() {},
    warn: function() {},
    error: function() {},
  };
}