Firebug Tip: console.log([label, value]);

Posted by Dan on Feb 27, 2008 @ 11:26 AM

[UPDATED: Thursday, February 28, 2008 at 8:02:17 AM]

I thought maybe this was a tip worth blogging. I like to use labels in my debug information as it helps me to quickly identify the debug statement that generated the output. Appending a label string to a simple value is easy enough in JavaScript, as it'll automatically be converted to a string. However, this doesn't work for complex values. You can place the label on a separate line, but I like to try to keep things to one line whenever possible. The way I do this is to use an array to output my label first and then the value:

console.log(["my label", complexObject]);

This gives you the benefit of generating a label and a value all on one line. I find the syntax very easy to read in the Firebug console and it keeps everything on one line—just the way I want it. The output will look like:

["my label", {...}]

Hopefully someone else will find this tip useful.

For those of you who want a Firebug to output a hyperlink to the line that invoked the message, you might want to use console.debug() instead.
Categories: JavaScript


  • Check out console.dir() then..

  • @Neil:

    I prefer console.log(). Also, console.dir() does not output a label either. The dir() method is great if you want to actually output the entire object. However, I'm often placing debug calls throughout a complicated script. Being able to generate a label with the output helps me know where things are going wrong.
  • Tx for the info.

    The only bad things with console.log methods is that you can't (or I can't find the way to) get the concext of the call to the precedent method in the stack that generate the call to it. I want to develop a generic Log class and want to log to Firebug, but all my output is traced with the same line, same file ... the one of my logger class, not the originating line.

    Anyone ?
  • @Tek:

    Not sure if this answers your question, but the console.trace() statement will dump out an interactive stack trace to the call. If you call the method from a generic logging message, it will point to your logging method as the end point, but you can just use the console.trace() whenever you need the exact stack.
  • Dan > I will take a look to that tomorrow. I'll give you any interesting feedback.

Comments for this entry have been disabled.