Managing Debug Output with Google Chrome Console API

   Front End Development
Managing Debug Output with Google Chrome Console API

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.


Like What You See?

Got any questions?