Rufus Rufus - 6 months ago 92
Javascript Question

A proper wrapper for console.log with correct line number?

I'm now developing an application, and place a global

switch. I would like to wrap
for more convenient usage.

//isDebug controls the entire site.
var isDebug = true;

function debug(msg, level){
var Global = this;
if(!(Global.isDebug && Global.console && Global.console.log)){
level = level||'info';
Global.console.log(level + ': '+ msg);

debug('Here is a msg.');

Then I get this result in Firefox console.

info: Here is a msg. debug.js (line 8)

What if I want to log with line number where
gets called, like
info: Here is a msg. main.js (line 2)


This is an old question and All the answers provided are overly hackey, have MAJOR cross browser issues, and don't provide anything super useful. This solution works in every browser and reports all console data exactly as it should. No hacks required and one line of code Check out the codepen.

var debug = console.log.bind(window.console)

Create the switch like this:

isDebug = true // toggle this to turn on / off for global controll

if (isDebug) var debug = console.log.bind(window.console)
else var debug = function(){}

Then simply call as follows:

debug('This is happening.')

You can even take over the console.log with a switch like this:

if (!isDebug) console.log = function(){}

If you want to do something useful with that.. You can add all the console methods and wrap it up in a reusable function that gives not only global control, but class level as well:

var Debugger = function(gState, klass) {

  this.debug = {}

  if (gState && klass.isDebug) {
    for (var m in console)
      if (typeof console[m] == 'function')
        this.debug[m] = console[m].bind(window.console, klass.toString()+": ")
    for (var m in console)
      if (typeof console[m] == 'function')
        this.debug[m] = function(){}
  return this.debug

isDebug = true //global debug state

debug = Debugger(isDebug, this)

debug.log('Hello log!')
debug.trace('Hello trace!')

Now you can add it to your classes:

var MyClass = function() {
  this.isDebug = true //local state
  this.debug = Debugger(isDebug, this)
  this.debug.warn('It works in classses')