Advanced JavaScript Console Logging for Developers

Advanced JavaScript Console Logging for Developers

Developers need to debug their applications to find errors and issues. Knowing to use advanced console logging is a handy tool for developers.

Featured on Hashnode

The flood of software innovation over the past 20 years would not have been possible without agile working. The concept of releasing fast, taking feedback, and building back better has birthed the iPhone, social networks and the Cloud. The world would be a slower, duller place without it.

But we can’t do Agile unless we can get real insights from our user’s screens, and here, the developer tools published by Safari, Chrome and other browsers are crucial. These tools show us how our app looks out in the wild and enable us to fix it on the fly without relying on source code.

Of all the many possibilities offered by dev tools, the Console tool, which helps developers log application messages, is arguably the most important. And in this article, we’ll break into several exciting use cases of the Console tool, including advanced usages to help you make decisions, analyze data and write code snippets before changing the source code.

First, let’s find the Console Tool using the developer tools shortcut

Simply open your favourite browser and press the F12 on your keyboard (if you’re on a Mac, you’ll need /fn + F12).

This should open the Developer Tools interface. Once you’ve found the Console tab, you can get started.

The Console tab of the Google Chrome browser’s Developer Tools.

Ok, on to the basics of console logging

JavaScript is the universal language of web applications, and you can use the Console web API to log messages into the browser’s console.

Here are some examples:

  • console.log: The log() method outputs a message to the browser’s console (in the Console tab).

  • console.info: If you want to log any informational message, you can use the info() method. Firefox will show a small “i” icon beside the message, to indicate it is an information message.

  • console.warn: The warn() method logs a warning message. This will be in a distinctive colour, so you can find the message quickly. The Chrome and Firefox browsers will also show an exclamation point icon beside the message to indicate the warning.

  • console.error: The error() method logs an error message into the console. This time the message will be in red.

  • console.debug: To output a message at the debug log level, you can use the debug() method. Please note you will not be able to see the debug messages if the console is configured to hide the debug messages.

console.log('This is a log message');
console.info('This is an info message');
console.warn('This is a warning message');
console.error('Err!!! It is an error message');
console.debug('Let us debug this!');

The output (in the Firefox browser)

Remember: you need to know what you’re logging

When you log into the console, you may only be interested in logging the values. No worries: we get that. You want to get the information as quickly as possible.

But without context, you may struggle to understand where the value comes from and what it relates to. For example, the following code has been created to log a user’s name, and will output atapas.

const userName = 'atapas';

console.log(userName);

But if you see the log and don’t see the code that’s produced it, you will likely be clueless about what atapas actually is.

Well fear not, because you can fix this problem in two ways.

First, you can pass a relevant message, and the value, as comma-separated arguments to the log() method. This will output a concatenated message (in other words, a series of words linked together), which may look much better than simply logging the value.

console.log('The user name is', userName);

The output will be The user name is atapas.

Alternatively, you can wrap the variable in the curly brackets and pass it to the log() method. This will output a JavaScript object, with the key as the variable name and the value in the console. Personally, I prefer this approach over the previous one, but each to their own.

console.log({userName});

The Output:

Filtering the log messages

When there are too many log messages, it’s worth filtering them to find the specific ones you are interested in. The message-filtering options differ from one browser to another, but they all do a similar job. You can filter log messages by typing the text into the filter text box. The log messages will filter based on the matching text as you type. In the image below, we’ve filtered messages matching the text status code.

You can also filter the messages by level using the console tab drop-down.

Grouping console messages

Keeping the console log messages loose may be confusing when debugging an issue. Alternatively, you can group the log messages contextually so they appear together.

The JavaScript console API provides two ways of doing this:

  • console.group: The group() method creates an inline group of the console messages. All subsequent messages to the group() method will be intended by a level until you call the groupEnd() method.

  • console.groupEnd: The groupEnd() method helps order the current group of messages.

In the example below, we have grouped a whole bunch of logs together:

console.group('Testing my calc function');
console.log('adding 1 + 1 is', 1 + 1);
console.log('adding 1 - 1 is', 1 - 1);
console.log('adding 2 * 3 is', 2 * 3);
console.log('adding 10 / 2 is', 10 / 2);
console.groupEnd();

And here is the output:

Please note that you can create as many groups as you want. But remember to provide a unique contextual message to the console.group() method for every group, so you can identify them without confusion.

You can also use the console.groupCollapsed() method to create a group, but in this case, the newly created group will be collapsed by default.

Tracing console messages

The console.trace() method logs a stack trace in the console. To maximise this function's benefits, finding the path of function calls executed to reach the console's place is useful.trace() method call.

In the following code snippet, we have a trace inside the inner() function, defined and invoked inside the outer() function.

function outer() {
  function inner() {
    console.trace();
  }
  inner();
}

outer();

This gives a rather nice pay-off: we can see a complete stack trace of the function calls.

Displaying console messages as table

You can log complex data structures as tabular data into the console. When doing so, use the console.table() method to represent complex JSON data in the row-column fashion.

The table() method shows the user’s data in a table format.

By default, the table() method will display all elements in the rows. You can restrict this display with the help of an optional columns parameter.

// Will show only the value of "name" attributes in each row
console.table(users, ["name"]);

Console expressions

Sometimes you may have to repeatedly use a JavaScript expression in the console. This might seem a bit time-consuming, but you can pin one or more expressions at the top of your console to make it easier. The expression value gets updated in real-time.

To create an expression, open the console tab and click the ‘eye’ icon. A text box will open for you to type in the expression. Then press the Enter key to save it.

Formatting console log messages

You can go a bit funky with the log message formatting and styling in the browser console if you want.

The console supports the application of multiple format specifiers. In the table below, you can see the supported ones now.

SpecifierDescription
%sFormat a variable as a string
%dFormat a variable as an integer
%fFormat a variable as a floating-point number
%oIt can be used to print a DOM Element
%0Used to print an object representation
%cUsed to pass CSS to format a string

Let’s look at a quick example: We’re formatting a message with string and integer values in the code snippet below. We are also passing CSS format to style the message.

console.log(
  '%c I have %d %s',
  'color: green; background:black; font-size: 20pt',
  3,
  'Bikes!'
)

And here’s the output:

Preserving console log messages

If you lost your log messages every time you navigated to the new pages of your application, it would be a serious hassle – not to mention a distraction as you attempt to hone, tweak and polish your app.

But there’s an easy way to preserve them. Simply click on the gear icon to open the settings panel. In the settings panel, you will find a setting called Preserve log. Click on the checkbox in front of it to enable the setting.

Console time

Time is one of the most decisive factors in the success or failure of an application: our users expect lightning, and they’ll turn their backs if we don’t deliver.

Thankfully, the browser console can help us measure the execution time of each function before we embed it into our source code file. In fact, the JavaScript console API provides two important time-related methods:

  • console.time: The time() method starts a timer for you and runs it until you call the timeEnd() method. The time() method takes a unique name as an argument to identify the timer to end it.

  • console.timeEnd: The timeEnd() method… well… it does exactly what it’s name would suggest.

Here’s an example where we calculate the time to retrieve the last name value a billion times.

function test time() {
  var users= [
    {
      firstname: "Tapas",
      lastname: "Adhikary",
      hobby: "Blogging"
    },
    {
      firstname: "David",
      lastname: "Williams",
      hobby: "Chess"
    },
    {
      firstname: "Brad",
      lastname: "Crets",
      hobby: "Swimming"
    },
    {
      firstname: "James",
      lastname: "Bond",
      hobby: "Spying"
    },
    {
      firstname: "Steve",
      lastname: "S",
      hobby: "Talking"
    }
  ];

  var getName = function (user) {
    return user.lastname;
  }

  // Start the time which will be bound to the string 'loopTime' 
  console.time("loopTime");

  for (let counter = 0; counter < 1000 * 1000 * 1000; counter++) {
    getName(users[counter & 4]);
  }

  // End the time tick for 'loopTime
  console.timeEnd("loopTime");
}

The output:

loopTime: 2234.032958984375ms

Store As a global variable

In real-world programming, we deal with a bigger chunk of JSON objects as the response to API calls, and we might want to pick a tiny portion for granular analysis and improvement.

The console tool allows us to save any portion of the JSON object as a Global Temporary Variable. You can use this variable later in the console panel for computations.

Check out the example below. Note that we’re saving the users array as a temporary variable and using it further.

Multi-Line console messages

Sometimes you may find it annoying to type multi-line expressions in the console panel, particularly when you’re in a sprint or working to a tight deadline.

To enter multiple lines in the console panel, press shift and enter key combinations at the end of a line to continue with the execution of each line. Finally, you can press the enter key to complete the process.

Displaying an interactive list of object properties

You can use the console.dir() method to display an interactive list of object properties. In some browsers like Google Chrome, the console.log() method also prints objects and arrays as interactive lists, but it doesn’t show their type until you expand the output.

console.log(['Apple', 'Orange']);

The output:

Now try the console.dir() method instead.

console.dir(['Apple', 'Orange']);

Console utilities

The console tool has several utility APIs to select, inspect, and monitor DOM. Note that you can only run these utility commands from the dev tools console panel: you can’t run them with external scripts.

$0: Reference a node

The $0 utility command returns the recently selected node in the Elements panel, so you can refer to it and perform further debugging and computations.

Check out the example below. It shows how we select and use a DOM element from the Elements panel in the Console panel.

$_: Refer to previous execution output

The $_ utility command returns the value of the expression you executed recently. Take a look at the image below to understand how to use the command in the console.

$: Query selector

The $ utility command works like document.querySelector(), returning the reference to the first DOM element with the specified CSS selector.

The example below shows the usage of the $ command to select the first image DOM element.

$$: Query selector all

The $$ utility command works like document.querySelectorAll() to return an array of elements that match the specified CSS selector. The example below shows the usage of the $$ command to select all the DOM element that represents images.

The clear() method

The clear() method will clear the console.

And finally: getting logs From Your customers

When discussing JavaScript console logging in this article, we’ve focused on instances where console logs can be used to debug and troubleshoot issues on the physical device itself.

However, our users may be spread all over the world, so it’s important to have tools that can provide insight into the performance of an application on remote devices as well.

This is where Bugfender comes in.

Bugfender enables developers to gather logs from customer devices remotely, so we get a comprehensive view of an application’s performance even when the user is in a different continent.

Bugfender is available as a Javascript package you can integrate into your Javascript application, with integrations with multiple frameworks. Here are some examples:

To conclude

We hope this article helps you get better information from your users and log these insights more accurately.

But there are loads more we can discuss regarding dev tools. While the console panel is powerful, it is still a tiny part of the Developer Tools and JavaScript debugging ecosystem using the browser.

If you want to explore the topic further, here’s a great piece to read next.

If you are looking for a complete guide to learning JavaScript, here is one for you.

This article was Originally Published on Bugfender.

Bugfender is a log storage service for application developers. It collects everything happening in the application, even if it doesn’t crash, in order to reproduce and resolve bugs more effectively and provide better customer support. Get started with Bugfender from here.


Before We End...

Thanks for reading it. I hope it was insightful. If you liked the article, please post likes and share it in your circles.

Let's connect. I share web development, content creation, Open Source, and career tips on these platforms.

Did you find this article valuable?

Support Tapas Adhikary by becoming a sponsor. Any amount is appreciated!