Skip to content
  • Services
  • About
  • Partners
  • Work
  • Insights
  • Careers
  • Contact
  • Services
  • About
  • Partners
  • Work
  • Insights
  • Careers
  • Contact
March 10, 2015

Managing Debug Output with Google Chrome Console API

Web and Mobile Development

Although everyone has their own preference and style for debugging their web applications, we usually have at least one technique in common. At some point we’re going to write content to the console in the hopes of accurately telling the story of what’s happening in our application. This post will explore how best to exercise the features of the Google Chrome Console API to support this.

Console API vs Command Line API

When you review the API documentation on the Google Chrome DevTools site, the first thing to understand is where you can use certain features. While the Command Line API can only be used in the console itself, the Console API allows you to leverage its features in both your application code and the console itself. There is a slight exception to this rule which we’ll explore later on.

Writing Output

The Console API offers a number of methods for writing output including: console.error, console.warn, console.info, console.log and console.debug. Each of these methods share common functionality that can be used to communicate conditions in your application.

When writing output to the console, make sure you use each and every one of these output methods for the given condition. You’ll see the benefit of this as your application grows, and you’re reviewing larger sets of messages. Classifying messages properly will also allow you to effectively use the console filter toolbar highlighted in Figure 1 below.

figure-1

Formatting Output

As your application grows, you’ll most likely be producing more debug output that needs to be reviewed. One of the best ways to manage this and maintain its usefulness is to understand the formatting options you have at your disposal.

Grouping

While the basic console output methods work great, over time you may desire a better way of organizing the information displayed. Perhaps you want to collect a group of messages for a certain function of your system (creating users, submitting orders etc). The Console API offers the console.group, console.groupCollapsed and console.groupEnd methods to logically group a set of messages into expandable output which can enhance the organization of your debug output. Grouping output always begins with either the console.group or console.groupCollapsed method. The groupCollapsed method is different because it will default to show the content in a collapsed state.

The example below gives a sample usage of grouping output with the result shown in Figure 2.

    console.group('User');
        console.info('creating user');
  
        var u = new User('Nigel', 'Bitters');
  
        console.info('User: %O created successfully!', u);
  
        // other user related activities...
    console.groupEnd();

figure-2

Dumping Data

When debugging our applications we’re most certainly going to want to inspect data. However depending on the size and complexity of the data it does stand the chance of being a little unwieldy to review in the console. In circumstances such as this, the console.table method can be useful.

Formally defined in the Command Line API, console.table is the oddball that also works in the Console API. This method produces sortable output that is easy to digest and is great to use when reviewing a collection of objects. A restriction to using console.table is that if you have a lot of columns you want to produce, there is no horizontal scrolling of data. However the method does allow you to specify which columns to render which can help mitigate this.

The example below defines a set of data that is dumped in a table, first showing all columns of data, then restricting output to just the lastName and type properties. The result is shown in Figure 3.

    var data = [
        { firstName : 'Nigel', lastName : 'Bitters', type : 'admin' },
        { firstName : 'Sammy', lastName : 'Hamm', type : 'user' },
        { firstName : 'Mickey', lastName : 'Mouse', type : 'user' }
    ];
  
    // show all data
    console.table(data);
  
    // show only the 'lastName' and 'type' columns
    console.table(data, ['lastName', 'type']);

figure-3

Formatting

All of the output methods (error, warn, info, log and debug) offer the capability to format the messages it produces. With all the different types of data we encounter in our web applications, this is a powerful feature to leverage.

Using format specifiers, we can render data as strings (%s), integers (%d or %i), floats (%f), JavaScript objects (%O) and even DOM elements (%o). The code example below demonstrates each of these formats with the result demonstrated in Figure 4.

    var user = {
        name   : 'Nigel Bitters',
        age    : 52,
        weight : 210.323
    };
  
    console.log('Name: %s, Age: %i, Weight: %f', user.name, user.age, user.weight);
  
    console.log('document.body: %o, user: %O', document.body, user);

figure-4

Note that DOM element and JavaScript object output is shown in a collapsed state by default. Figure 4 shows this output expanded to demonstrate the data inspection capabilities.

Styling

There is one more format specifier that we left out of the last section. It turns out that we can also style our output using CSS styles with the %c format specifier. Say for example we want to highlight a critical error condition in our code. The code below demonstrates this with the result shown in Figure 5.

console.log('%cSomething very nasty just happened', 'background-color:red;color:white;');

figure-5

The idea of styling our console output is powerful but also a good candidate for abuse. Each developer on a project might have their own idea of what styles to apply to make their own messages stand out. Additionally, defining styles like this can also be a little cumbersome. We can shorten up the definition of these styles and introduce consistency by defining a simple library of styles to use throughout our app as shown below.

    var __ = __ || {
        error : 'background-color:red;color:white;',
        warn  : 'background-color:yellow;font-weight:bold;',
        info  : 'background-color:blue;color:white;'
    };
  
    console.log('%cSomething very nasty just happened', __.error);

Conclusion

The Console API is a small, but powerful part of what the Google Chrome DevTools suite has to offer. For a deeper dive, check out the official documentation. Do you have a favorite trick you use to wrangle the console? If so, drop a comment below.

Posted in Web and Mobile Development
Share this

Brice Mason

Brice Mason is a speaker and published author with over 10 years of experience building software. A solutions based problem solver, Brice has exposure to working on government contracts, as well as experience in the private sector with large and small businesses.
Follow

Related Posts

  • Google Announces JSON-LD Compliance at Google I/O
    Google Announces JSON-LD Compliance at Google I/O

    Google announced JSON-LD compliance for Schemas in their web apps, particularly for GMail, Google Search,…

  • Google Announces JSON-LD Compliance at Google I/O
    Google Announces JSON-LD Compliance at Google I/O

    Google announced JSON-LD compliance for Schemas in their web apps, particularly for GMail, Google Search,…

Subscribe to the Modus Newsletter

Receive the latest insights from our team each month.

Let's Chat

If forms aren’t your thing, you can always call us (+1-855-721-7223).

Modus-Logo-Primary-White.svg
  • Services
  • About
    • Newsroom
  • Partners
  • Work
  • Insights
    • Blog
    • Modus Labs
  • Careers
Virginia (US)

12100 Sunset Hills Road
Suite 150
Reston, Virginia, 20190
Tel: +1-855-721-7223

California (US)
12130 Millennium Dr

Los Angeles, CA 90094

Missouri (US)
609 E High St

Jefferson City, MO 65101

Romania

Str. Mihai Veliciu, no. 17
Cluj-Napoca, Romania
Tel: +40-0786-887-444

Costa Rica

2nd Floor, Plaza Koros, Av 3
San José, Santa Ana, Costa Rica

© 2021 Modus. All Rights Reserved.

Privacy Policy | Accessibility Statement | Sitemap

Scroll To Top
This website uses cookies.
These cookies are used to collect information about how you interact with our website and allow us to remember you. We use this information in order to improve and customize your browsing experience, and for analytics and metrics about our visitors both on this website and other media. To find out more about the cookies we use, see our Privacy Policy.

Accept
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Save & Accept