JavaScript Logging Basic Tips

In the past few years, JavaScript has evolved in several ways and has come a long way. With the evolving technology, machines are becoming more powerful, and browsers are getting more robust and compatible. In addition, Node.js’s recent development for JavaScript’s execution on servers, JavaScript has been getting more and more popular than ever before. Today, web developers continue to create more complex applications by pushing the boundaries with JavaScript execution and trying out new things.

A logging functionality is crucial for every programming language. Although JavaScript has a console.log for performing basic debugging functions, its browser’s console comes with several other functions to perform debugging. As the scale of a codebase grows, one’s ability to efficiently debug a code gets increasingly critical. To learn more about multiple other debugging functions beyond console.log, have a look at this useful documentation for the browser console.

In today’s article, we shall see some of the crucial aspects of client-side JavaScript logging errors, client-side vs server-side logging, JavaScript built-in logging methods, and more. So, let’s get right into it.

#1 Client-side vs Server-side Logging

You have complete access to the console when you are doing local development. This access allows you to pursue stack traces, recreate errors, interpret cryptic error messages, and debug your heart’s content. However, when the application or the page reloads, all of the console’s content disappears. Even though this is useful during the development process, one does not have access to the console’s messages once they have published or released their code, and it is already running on the user’s machine.

Therefore, in such situations having a way to send your code’s several error messages from a client to a server for whom you have access would be extremely useful. A myriad of tools are available for such use cases and situations called logging frameworks. These tools gather or collect all the error messages occurring on the client-side and package them up effectively. Then they are sent to a storage location for whom you have access once they are nicely bundled up.

Therefore, client-side logging directly brings the entire error management platform from the server you have access to the user’s browser. However, when the logging is enabled on your server session and the software records the web browser’s behaviour on your server, it is referred to as server-side logging. The unresolved errors on the client-side logging are automatically picked up and offer a piece of detailed information about the environment. It bypasses logging to a developer’s server and instead logs the errors directly to the user or the client. Such direct logging to the client is a beneficial tool to offer immediate support to the customers.

#2 What are some of JavaScript’s built-in logging methods?

During the initial stage, developers often get comfortable with the console.log() function the first time they use JavaScript. When you put it on your desired location in a code, it provides contents and information of the term you put within the parentheses.

However, there is a complete array of methods on the console object that are usually underutilized but are extremely beneficial and useful.

Message Levels

JavaScript supports logging messages at several different levels, just like other programming languages. The logging message levels provided and supported by JavaScript are as follows:

1.) Plaintext

The method for plaintext is console.log() that outputs unstyled plain text, as the name suggests.

2.) Info

The method for this message level is console.info(). It typically outputs text with a blue background colour.

3.) Warn

The method for the warn message level is console.warn(). This level is similar to console.log(); however, they need more of the developer’s attention and often comes with stack traces to help you in the debugging as well. You can usually use a console.warn() warning when something unanticipated happens. It typically provides the output of text in a yellow background colour.

4.) Error

The method for error message level is console.error(). You can use a console.error() message when a huge or an application-breaking error happens. This message typically provides an output of a text with a red colour background.

Examples of these message levels are:

console.log("this is a log message");
console.warn("this is a warning message");
console.error("this is an error message");

These messages are nothing but simple cues for you to incorporate quick debugging in the console. They all work in the same common manner, apart from offering different messages and visual styling.

Message Grouping

Just like you write your code with proper grouping and structure, you can also structure your log output through message grouping. In order to create collapsible chunks of your log messages in the console, you can simply use console.group() and console.groupEnd() methods.

Separating log messages is difficult, especially when all of those are present in a common hierarchy within the console. However, through console.group(), you can improve your log message’s readability by organizing them into distinct groups.

console.group() and console.groupEnd() supports nesting, where console.group() accepts label as its parameter label, and messages that are placed between these two are grouped hierarchically and nicely.

For example, let us have a look at the following code:

console.group("This is a Group Heading");
console.log("This is a first line");
console.log("This is a second line");
console.log("This is a third line");
console.groupEnd();

This code snippet will group the lines between console.group() and console.groupEnd() in an organized manner, under the heading “This is a Group Heading” for better visualization and improved text readability. This organized grouping of log messages also helps you find messages you require quickly, with no hassle, and without wasting your time scanning and scrolling.

Code Timing

There are several reasons behind timing your code and knowing how much time does a code or a specific process within a code takes. Fortunately, to know these timings, you do not have to instal a third-party application or use any random tool to get basic timing functionality.

Let us take an example of the following code:

console.time("Timer Test Process");

// perform some process here
console.timeEnd("Timer Test Process");

JavaScript provides three functions to let you experience stopwatch functionality in your browser’s console. console.time() starts the timer with the “Timer Test Process” label. Following this, the console.timeLog() logs the current timer value, and the console.timeEnd() stops the particular timer once the same “Timer Test Process” label is passed.

One can have thousands (10,000) of timers at the same time on one page with different labels, once the console.timeEnd() function is called the timer is permanently deleted from the memory. In case you further try to call console.timeEnd() again, it will throw a warning message at the output. With this functionality, you do not have to install or use a third-party timer functionality; and instead, use this simple running time function with ease to know your code’s processes time.

Catch errors efficiently with try...catch...finally

JavaScript developers implemented a tool to efficiently handle an error-prone code with the help of a try...catch...finally statement.

The code snippet looks like this:

try {
    // code lines 
} 
catch (error) {
    // code to run for finding our any error
}
finally {
    // the code continues to run irrespective of the error presence
}

This statement enables you to enclose potentially error-prone code in a try block, catch, and logs an error if there is one, allowing the program to continue working in the finally block.

try-catch-finally
try-catch-finally

This statement and pattern help coders effectively create error boundaries with their programs to ensure that the program does not crash because of one or multiple errors.

Conclusion

Effectively and efficiently logging is one of the most crucial skills every web developer wish to possess. Client-side logging functionality is only a small part of the entire development process, yet an important part. Using the logging functionalities helps developers develop codes more efficiently. To learn about more JavaScript functions found on the browser’s console, navigate to the MDN’S documentation to have an in-depth overview of them.

Let us conclude what we learned in this article with these key takeaways:

  • During the development process of your code, use console.log() and its colour-coded multiple variations to enhance your log output’s readability.
  • To streamline and organize your logging activities, use console.group() to prevent wasting time searching messages through the console messages.
  • Use console.time() to optimize performance, identify processing bottlenecks, and know the time required for a process code to run. Finally, use try...catch...finally statement to reduce the chances of potential program-breaking and other harmful errors.

Monitor Javascript Errors with Atatus

Track entire JS errors that slows down your application and get to know the root-cause of the issue with the complete stack-trace and exact line of the code where an error has occurred with Atatus.

Browser Dashboard
Browser Dashboard

Features that Real User Monitoring offers:

  • Google's Core Web Vitals
  • Page Monitoring
  • Single Page Application Monitoring(SPA)
  • AJAX Monitoring
  • User Journeys
  • Error Tracking

With the above listed features you can monitor your complete front-end code and fix the issues at the right time to optimize end-user experience.

Sign Up for free. 14-day unlimited free trial. No credit card required!!!

Share your thought about Javascript Logging in the below comment section.


Vaishnavi

Vaishnavi

CMO at Atatus.
Chennai

Monitor your entire software stack

Gain end-to-end visibility of every business transaction and see how each layer of your software stack affects your customer experience.