Firebug Tutorial - Logging, Profiling and CommandLine (Part I)

Firebug Tutorial

Section 1: Console Tab : Logging, Profiling and CommandLine (Part II)

Overview of Console Tab

This tab is mainly used for logging. It also can be used as CommandLine window (like immediate window in Microsoft Visual Studio) while you are debugging the Javascript. It can be used for monitoring the execution of Javascript code by using Profiling service.

The following topic will be covered in this section.

  • Logging in Firebug (with String Substitution pattern )
  • Grouping the logs or messages
  • console.dir and console.dirxml
  • Assertion ( console.assert() )
  • Tracing ( console.trace() )
  • Timing ( Measuring the time of your code)
  • Javascript Profiler (An introduction in this tutorial, the details will be covered in next tutorial.)

#1. Logging in Firebug

Firebug supports logging in Console tab. So, you don’t need to use alert(’something’) or document.write(’something’) anymore.

There are five types of logging in Firebug.

  • console.log : Write a message without icon.
  • console.debug : Writes a message to the console, including a hyperlink to the line where it was called
  • erroricon.png console.error() : Writes a message to the console with the visual “error” icon and color coding and a hyperlink to the line where it was called.
  • infoicon.png console.info() : Writes a message to the console with the visual “info” icon and color coding and a hyperlink to the line where it was called.
  • warningicon.png console.warn() : Writes a message to the console with the visual “warning” icon and color coding and a hyperlink to the line where it was called.

Example Code:

  • Open the htm file called “Plain HTML” or create one HTML file.
  • Paste the following code with <body> tag.

<script language="javascript" type="text/javascript">
console.log('This is log message');
console.debug('This is debug message');
console.error('This is error message');
console.info('This is info message');
console.warn('This is warning message');
</script>

You will get the following output. If you click on hyperlink (”test.htm” in this case), it will take you to script tab and will highlight the line that wrote this message.

basic-logging-concept.jpg

String Substitution Patterns

String substitution parterns can be used in console.log, console.info, console.debug, console.warn and console.error . You can use the same way that we used in C/C++.

%s String
%d, %i Integer (numeric formatting is not yet supported)
%f Floating point number (numeric formatting is not yet supported)
%o Object hyperlink

Example :

Note: I will use console.log in the example below even all console objects (console.log, console.info, console.debug, console.warn and console.error ) support string substitution.

  • Remove “script” tag that we pasted for the previous example.
  • Paste the code below within <body> tag.

<script language="javascript" type="text/javascript">

//This is for normal string substitution " %s, %d, %i, %f".
console.log("My Name is <strong>%s</strong>. My Date of Birth is <strong>%dth %s, %i</strong>. My height is <strong>%f</strong> m.", "Nicolas Cage", 7, 'January', 1964, 1.8542);

function Foo(){
this.LeftHand = function(){
return "Left Hand";
}
this.RightHand = function(){
return "Right Hand";
}
}

//This is for object "%o".
var objFoo = new Foo();
console.log('This is <strong>%o</strong> of Foo class.', objFoo);

</script>

console-string-substitution1.jpg

If you are using %o in your log, the object will be shown as a hyperlink in green color. This hyperlink is linked to the DOM tab. So, If you click “object” in second line, you will see the list of properties of that object (LeftHand and RightHand in this case.)

#2. Grouping

Firebug allows you to group the message or log in Console tab. If you have some many logs in your code, you can probably divide your log into small group or subgroup

Example ~


<script language="javascript" type="text/javascript">

var groupname = 'group1';
console.group("message group : %s " , groupname);
console.log("log message 1 from %s", groupname);
console.log("log message 2 from %s", groupname);
console.log("log message 3 from %s", groupname);
console.groupEnd();

groupname = 'group2';
console.group("message group : %s " , groupname);
console.log("log message 1 from %s", groupname);

var subgroupname = 'subgroup1';
console.group("message group : %s " , subgroupname);
console.log("log message 1 from %s", subgroupname);
console.log("log message 2 from %s", subgroupname);
console.log("log message 3 from %s", subgroupname);
console.groupEnd();

console.log("log message 3 from %s", groupname);
console.groupEnd();

</script>

group-message.jpg

#3. console.dir and console.dirxml

  • console.dir : It can be used for getting all properties and methods of a particular object. According the example below, we can get the Model (property) and getManufactor (method) of Car object by using console.dir(); You can also pass the object of HTML element (eg: console.dir(document.getElementById(’tbl1′)); ) instead of objCar and let’s see the result. (You will get all properties and methods of the HTML table called “tbl1″).
  • console.dirxml : print the XML source tree of HTML element.

<table id="tbl1" cellpadding="0" cellspacing="0" border="0">
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
</table>
<script language="javascript" type="text/javascript">
//Create a class
function Car(){
this.Model = "Old Model";

this.getManufactor = new function(){
return "Toyota";
}
}

//Create a object
var objCar = new Car();

//Firebug
console.dir(objCar);
console.dirxml(document.getElementById('tbl1'));

</script>

console-dir.jpg

#4. Assertion ( console.assert() )

You can use console.assert() to test whether an expression is true or not. If the expression is false, it will write a message to the console and throw an exception.

Example :


<script language="javascript" type="text/javascript">
function whatIsMyAge(year){
var currYear = 2007;
return currYear - year;
}

var yearOfBirth1 = 1982;
var age1 = 25;
console.assert(whatIsMyAge(yearOfBirth1) == age1);

var yearOfBirth2 = 1982;
var age2 = 11;
console.assert(whatIsMyAge(yearOfBirth2) == age2); //You should get the error here.
</script>

assertion-failure.jpg

#5. Tracing ( console.trace() )

This function is very interesting. Before I tell you the way that I understand, let’s take a look what console.trace does exactly in official website.

console.trace()

Prints an interactive stack trace of JavaScript execution at the point where it is called.

The stack trace details the functions on the stack, as well as the values that were passed as arguments to each function. You can click each function to take you to its source in the Script tab, and click each argument value to inspect it in the DOM or HTML tabs.

This function will tell you about the route information from start point to end point. If you are not clear what I mean, let’s take a look at the sample code and the result.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Firebug</title>
<script language="javascript" type="text/javascript">
function startTrace(str){
return method1(100,200);
}
function method1(arg1,arg2){
return method2(arg1 + arg2 + 100);
}
function method2(arg1){
var var1 = arg1 / 100;
return method3(var1);
}
function method3(arg1){
console.trace();
var total = arg1 * 100;
return total;
}

</script>
</head>
<body>
<input type="button" value="Trace" onclick="startTrace('Result');"/>
</body>
</html>

trace.jpg

Suppose: we wanna know how “method3″ function is invoked. So, we put this code “console.trace()” in that method. then, we run the program and we got the result as picture above. If we read the result from bottom to top, we will see “onclick(click clientX=34, clientY=26)”. That means the execution of Javascript started at on click event of button. then, we got “startTrace(”Result”)” in second line. That means startTrace function is invoked after firing onclick event and the parameter is “Result”. If we keep on checking from bottom to top, we will figure out the completed route from onclick event to method3.

If you wanna test more, you can move this code “console.trace()” to method2(). then, firebug will give the new route from onclick event which is a started point to method2() which is the end point.

I think that it’s pretty useful if you are debugging the other developer’s source code and you have no idea why this function is invoked.

Let me know if you are not clear what I’m trying to explain about console.trace();.

#6. Timing ( Measuring the time of your code)

You can use console.time(timeName) function to measure how long a particular code or function take. This feature is very helpful if you are trying to improve the performance of your Javascript code.

Example :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Firebug</title>
<script language="javascript" type="text/javascript">
function measuretheTime(){
var timeName = 'measuringTime';
console.time(timeName);

for(var i=0;i&lt;1000;i++){
///do something
for(var j=0;j&lt;100;j++){
//do another thing.
}
}

console.timeEnd(timeName);
}
</script>
</head>
<body>
<input type="button" value="Trace" onclick="measuretheTime();"/>
</body>
</html>

Result : measuringTime: 16ms

#7. Javascript Profiler

You can start the profiler thought code (console.profile(’profileName’)) or by clicking “Profile” button from “Console” tag. It can be used for improving the performance of Javascript. It is similiar to the console.time() function but profiler can give your more advanced and detailed information.

I will tell you about this more details in next tutorial (Part2) . I hope you all are clear about this tutorial. If you have any comment or suggestion, please drop a comment.. Thanks. C ya tomorrow.

Reference ~


50 Comments so far »

  1. Pye Phyo Set said

    am September 9 2007 @ 3:44 pm

    Hi,

    Good post. Carry on!

    C ya 2morrow

  2. Michael Sync said

    am September 9 2007 @ 4:12 pm

    thanks.. sett sett. :)

  3. Myo Kyaw Htun said

    am September 10 2007 @ 1:25 am

    Cool ! waiting for another tutorial.

    btw, Mike, which plugin you’re using for code ?

  4. qureyoon said

    am September 10 2007 @ 1:44 am

    this is very helpful ! i only knew as far as the point 1. Logging :P never knew it can be grouped !

    *bookmarked !

  5. Kushan Jayathilake said

    am September 10 2007 @ 3:26 am

    thx bud, this was really helpful carry on your work
    im waiting for the next tutorial

  6. Firebugging, und nocheinmal » Code Candies said

    am September 10 2007 @ 7:19 am

    [...] Tool Firebug gebracht: ein etwas in die Tiefe gehendes Tutorial dazu gibt’s bei Michael Sync. Es geht über die einfachen console-Befehle hinaus und zeigt bspw. wie man in [...]

  7. Aaron Bassett said

    am September 10 2007 @ 8:59 am

    I wrote an actionscript class which supports most of the console methods mentioned above. It allows you to use these methods within your actionscript/flash and see the output within Firebug in the browser.

    You can download the class or see an example here: http://foobr.co.uk/2007/02/debug_flash_with_firebug/

  8. Michael Sync said

    am September 10 2007 @ 9:58 am

    @Myo Kyaw Htun,

    >>btw, Mike, which plugin you’re using for code ?

    that one is wp.com default one. I’m not sure which one wp.com guys are using… but there is one similar or same plug-in for wordpress.org blog..

    chk-out this link..
    http://michaelsync.net/2007/09/06/syntaxhighlighter-plug-in-posting-source-code-in-wordpress-org/

    I have tested in my local machine and it works great… :)

    @Kushan Jayathilake,qureyoon

    Thanks. :)
    @Aaron Bassett

    Yeah. I have checked your blog.. it is very interesting… thanks for your link…

  9. Myo Kyaw Htun said

    am September 10 2007 @ 2:08 pm

    Mike, Thank you :) I’m going to try it out!

  10. Binny V A said

    am September 10 2007 @ 4:11 pm

    Thanks for the write up - waiting for part two.

  11. Metaholic » Blog Archive » Firebug Tutorial - Logging, Profiling and CommandLine (Part I) « Michael Sync said

    am September 10 2007 @ 4:40 pm

    [...] Permalink | Source [...]

  12. Firebug Tutorial - Logging, Profiling and CommandLine (Part II) « Michael Sync said

    am September 10 2007 @ 7:18 pm

    [...] Logging, Profiling and CommandLine (Part II) 10Sep07 This tutorial is the part II of “Firebug Tutorial - Logging, Profiling and CommandLine“. (If you haven’t read the part I of this tutorial, I would recommend you to read it [...]

  13. links for 2007-09-11 « Simply… A User said

    am September 11 2007 @ 12:39 am

    [...] Firebug Tutorial - Logging, Profiling and CommandLine (Part I) « Michael Sync (tags: firebug javascript tutorial firefox debugging programming profiling debug **) [...]

  14. Skylog » Blog Archive » links for 2007-09-11 said

    am September 11 2007 @ 6:18 am

    [...] Firebug Tutorial - Logging, Profiling and CommandLine (Part I) (tags: programming) [...]

  15. wirtsi said

    am September 11 2007 @ 9:32 am

    nice …. exactly what i was looking for!

  16. » Tutorial acerca del manejo de Firebug | Informática Práctica | said

    am September 11 2007 @ 12:14 pm

    [...] tiempo de carga de una página, ver sus archivos CSS y Javascript, y un largo etcétera. Si quieres conocer ésta herramienta en profundidad, no dudes en visitar éste tutorial completo que encontré en del.icio.us. Es la primera parte, asi que estaré atento a la continuación del [...]

  17. Dean said

    am September 11 2007 @ 8:29 pm

    Nice one dude, hope to see more soon.

  18. 2con said

    am September 12 2007 @ 1:00 am

    this post was really helpful !
    I hope to next post more soon.
    Thanks!

  19. Urls Sinistras » Blog Archive » del.icio.us entre 05/09/2007 e 11/09/2007 said

    am September 12 2007 @ 8:02 pm

    [...] Firebug Tutorial - Logging, Profiling and CommandLine (Part I)Tutorial para se explorar ao máximo a extension FireBug. [...]

  20. links for 2007-09-16 | Patrick Kempf said

    am September 16 2007 @ 12:19 am

    [...] Firebug Tutorial – Logging, Profiling and CommandLine (Part I) « Michael Sync (tags: firebug firefox javascript tutorial debugging) [...]

  21. Tutoriales para aprender a usar Firebug said

    am September 16 2007 @ 10:53 pm

    [...] ello pone a nuestra disposición tres partes que explican diferentes aspectos de la aplicación (1, 2 y 3). Estad atentos porque la cosa promete continuar. Escrito a las 22:51 | Envia esta nota por [...]

  22. Tutorial de Firebug said

    am September 17 2007 @ 6:31 am

    [...] - Firebug Tutorial Parte 1 [...]

  23. Tutorial para aprender a usar Firebug « Cosas sencillas said

    am September 17 2007 @ 6:59 am

    [...] ello pone a nuestra disposición tres partes que explican diferentes aspectos de la aplicación (1, 2 y 3). Estad atentos porque la cosa promete [...]

  24. Actualidad, Entretenimiento y Humor » Tutorial de Firebug said

    am September 17 2007 @ 7:31 am

    [...] - Firebug Tutorial Parte 1 [...]

  25. Tutorial Firebug « Quest’s Blog said

    am September 17 2007 @ 8:29 pm

    [...] Firebug Tutorial - Logging, Profiling and CommandLine (Part I) Firebug Tutorial - Logging, Profiling and CommandLine (Part II) Firebug Tutorial - Using [...]

  26. mcdave.net » links for 2007-09-23 said

    am September 23 2007 @ 6:19 am

    [...] Firebug Tutorial - Logging, Profiling and CommandLine (Part I) « Michael Sync (tags: firebug firefox javascript tutorial debugging programming development profiling) [...]

  27. 出家如初,成佛有余 » Firebug 及yslow的相关资料 said

    am October 2 2007 @ 2:46 pm

    [...] Firebug Tutorial - Logging, Profiling and CommandLine (Part I) [...]

  28. 关于firebug和yslow的资料汇总帖 | 出家如初,成佛有余 said

    am October 5 2007 @ 2:23 pm

    [...] Firebug Tutorial - Logging, Profiling and CommandLine (Part I) [...]

  29. Michael Sync’s Firebug Tutorial @ Takealook said

    am October 8 2007 @ 7:08 am

    [...] 2: Logging, Profiling und CommandLine ( Part 1 [...]

  30. finch said

    am October 8 2007 @ 9:15 am

    whoa! this is exactly what i need .kudos to you mike! thanks

  31. Nachlese September 2007 - Die Seiten des Monats | Nachlese said

    am October 9 2007 @ 6:06 pm

    [...] Firebug Tutorial - Logging, Profiling and CommandLine Beim Debugging von Fehlern, insbesonderen bei Ajax-Anwendungen wird Firebug fast stillschweigend benutzt. Das Tool bietet jedoch mehr Funktionen, mit denen man u. U. schneller auf die Fehlerquelle aufmerksam wird. Dieser Beitrag erklärt insbesondere anhand von Beispielen, wie man mit Konsole umgeht. Weitere Beiträge werden folgen. [...]

  32. Best of September 2007 | Best of the Month said

    am October 9 2007 @ 7:12 pm

    [...] Firebug Tutorial - Logging, Profiling and CommandLineFirebug is probably the first choice when it comes to debugging JavaScript-based applications. This article gives a deep insight into the features of Firebug and shows how one can use the Console in web projects. [...]

  33. Best of September 2007 . said

    am October 9 2007 @ 8:35 pm

    [...] Firebug Tutorial - Logging, Profiling and CommandLineFirebug is probably the first choice when it comes to debugging JavaScript-based applications. This article gives a deep insight into the features of Firebug and shows how one can use the Console in web projects. [...]

  34. مدونة الدكتور نت » أرشيف المدونة » وصلات و مواقع - اكتوبر 2007 - said

    am October 10 2007 @ 4:28 am

    [...] درس استخدام FireBug : و هو إضافة للفايروفوكس تساعد المطورين على اكتشاف الاخطاء و تطوير المواقع . [...]

  35. firebug tutorial — award tour said

    am October 10 2007 @ 7:19 am

    [...] Firebug Tutorial - Logging, Profiling and CommandLine. advanced features for heavy javascript dev. [...]

  36. Christian said

    am October 11 2007 @ 7:48 am

    hi there!
    thanks a lot for this cool summary!

    i guess this will help me a lot in the future :)

  37. Michael Sync » Firebug Tutorial - Using Commandline API in Firebug said

    am October 13 2007 @ 9:09 am

    [...] is like console.dir() that I already mentioned in Part I. So, I think you already have some idea about what console.dir is and how to use. I’m not [...]

  38. Michael Sync » Firebug Tutorial - Logging, Profiling and CommandLine (Part II) said

    am October 13 2007 @ 9:10 am

    [...] tutorial is the part II of “Firebug Tutorial - Logging, Profiling and CommandLine“. (If you haven’t read the part I of this tutorial, I would recommend you to read the [...]

  39. Volcaniccep.Com » Firebug Tutorial - Logging, Profiling and CommandLine (Part I) said

    am October 28 2007 @ 1:10 pm

    [...] wrote an interesting post today on Firebug Tutorial - Logging, Profiling and CommandLine (Part I)Here’s a quick [...]

  40. How to Profile Greasemonkey Scripts with Firebug « // Internet Duct Tape said

    am November 13 2007 @ 6:35 am

    [...] Sync has a tutorial on using Firebug that describes the console.time() and console.profile() functions. The official website has a nice list of Firebug keyboard shortcuts [...]

  41. 行搏客 » 2007年9月最佳 said

    am November 16 2007 @ 9:54 am

    [...] Firebug Tutorial - Logging, Profiling and CommandLine Firebug is probably the first choice when it comes to debugging JavaScript-based applications. This article gives a deep insight into the features of Firebug and shows how one can use the Console in web projects. [...]

  42. blog-thing : How to Profile Greasemonkey Scripts with Firebug said

    am November 24 2007 @ 12:18 pm

    [...] Sync has a tutorial on using Firebug that describes the console.time() and console.profile() functions. The official website has a nice list of Firebug keyboard shortcuts [...]

  43. Dan said

    am December 16 2007 @ 10:41 pm

    Thanks for this. It’s very useful. I don’t see HTML elements take effect in my console output. I see the tags instead:

    My height is 1.8542 m.

    I tried to ensure something in my Firefox profile wasn’t causing this, but even using a fresh user profile creates the same result. Tags in the console are certainly not essential. I wonder if their support was dropped or if I had perhaps overlooked something. The official Firebug site makes no mention of HTML tags in console output.

    Thanks once more. Onto part two!

  44. Dan said

    am December 16 2007 @ 10:42 pm

    (retry) I see this in my console:

    My height is <strong>1.8542… etc.

  45. jo said

    am January 1 2008 @ 2:06 pm

    Mike, thanks so much for the illuminating tutorial. Very very useful.
    I have a question though. At work I also have to test the pages on IE. How does the console command behave in IE since it does not have Firebug?

  46. Michael Sync said

    am January 1 2008 @ 6:40 pm

    Yeah. there is no console in IE. So if you are writing the code, you should write like that


    if(window.console){
    console.log(”test”);
    }

    otherwise, you will get the error.

  47. Michael Sync » Liz called me an SOB said

    am January 19 2008 @ 11:03 pm

    [...] Firebug Tutorial - Logging, Profiling and CommandLine (Part I) [...]

  48. Designer said

    am March 20 2008 @ 2:37 pm

    Very nice tutorial. Thanks for sharing this!

  49. Web开发工具大集合——每个浏览器都有份的! | 网生代 said

    am May 12 2008 @ 9:04 am

    [...] 萤火虫 是Firefox上数一数二的好扩展,可作为web developer toolbar的补充工具。你可以用Firebug在线检查、监控、编辑网页上的HTML、CSS、JavaScript代码。他还提供一个脚本控制台,让JS编辑编的更简单。控制台对象包含了一大堆选项,允许你输出代码到控制台然后进行调试。Michael Sync提供一个更高级的操作指南,它可以知道你详尽地设置Firebug的选项。另外,Firebug上有一个带宽监视器,能让你清楚地看到某些代码占了多少带宽。 Firebug 下载地址:http://www.getfirebug.com/ [...]

  50. siddhartha said

    am June 25 2008 @ 1:27 am

    It will help you to improve JavaScript coding.

    Thanks
    Sid

Comment RSS · TrackBack URI

Leave a comment

Name: (Required)

eMail: (Required)

Website:

Comment: