2

I've written a very simple function to ensure ensure my applications do not break if I forget to remove a console.log().

Simply put:

myNamespace.log = function( msg ){
   if( window.console ){
      console.log(obj);
   }
}

It works like a charm. Alas, I very much liked the ability to see from which line of code and file my console messages came from. Is there a (chrome/FF friendly) way to get the file/line of code a function call?

Derek Adair
  • 21,846
  • 31
  • 97
  • 134
  • See [How to get JavaScript caller function line number? How to get JavaScript caller source URL? ](http://stackoverflow.com/questions/1340872/how-to-get-javascript-caller-function-line-number-how-to-get-javascript-caller-s). [scotts's answer](http://stackoverflow.com/questions/1340872/how-to-get-javascript-caller-function-line-number-how-to-get-javascript-caller-s/3444831#3444831) points to a cross-browser script that wraps all of the browser-specific methods. – Matthew Flaschen Dec 28 '10 at 22:12

1 Answers1

2

If it were my site, I'd use:

myNamespace.log = function( msg ){
  if( window.console && window.console.log && typeof window.console.log === "function" ){
    console.log(obj);
  }
}

I seriously doubt there's a browser-agnostic way to get source file line number.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • well I just realized it's for my personal use so chrome/FF would suffice for this particular functionality. What do the additional conditions in the if statement do? – Derek Adair Dec 28 '10 at 21:56
  • Check to make sure that "window.console" actually has a "log" property, and that the property is really a function you can call. Probably overly paranoid, but if you want to really make sure that stray "console.log" calls definitely won't cause an exception that'd be more insurance. – Pointy Dec 28 '10 at 22:16