- Getting Creative with the Console API!
- Author: Twitter Facebook
- Translator: Zavier Tang
The Console API is a constant part of debugging JavaScript programs, and most of the time we just use console.log() to do our job. But, you know what? We don’t have to. Don’t you find the single block output of console.log() annoying? In fact, you can make your Console better and more readable 💅.
Console.log()
Believe it or not, console.log() has some features of its own that you might not know about. Of course, its most basic use is to print logs. The only thing we can do is make it more readable!
Substitution string
The only thing closely related to the console.log() method is that you can use it with what are called alternative strings (String subs). This gives you the ability to use a specific expression in a string, which will be replaced by the supplied argument. As follows:
console.log("Object value: %o with string substitution",
{string: "str".number: 10});
Copy the code
The console results are as follows:
There are other forms of string substitution expressions:
%o / %O
– on behalf ofobjects
;%d / %i
– on behalf ofintegers
;%s
– on behalf ofstrings
;%f
– on behalf offloating-point numbers
;
However, you may be wondering why use such a feature at all? Without substituting strings, you can also easily pass multiple values to the printed log as follows:
console.log("Object value: ",
{string: "str".number: 10},
" with string substitution");
Copy the code
Perhaps, for strings and numbers, you can just use the literal form of the string. However, I would say that when doing some readable console log output, you need to output string formats well, and substituting strings (string subs) lets you do that easily! You must agree with the above choices. Instead of strings (String subs) it would be more convenient. As for string literals, they don’t have these handy features like ** replacing strings (String subs) **, and they don’t provide the same, nifty format for objects. But actually, if you’re just dealing with numbers and strings, you might prefer a different approach.
CSS
There’s another substitution string instruction that we haven’t seen before. It’s % C, and it allows you to apply CSS styles to your printed output! 😮
console.log("Example %cCSS-styled%c %clog!"."color: red; font-family: monoscope;".""."color: green; font-size: large; font-weight: bold");
Copy the code
The control results are as follows:
The example above uses the % c directive. As you can see, styles apply to everything after the %c directive. Close the use of styles by using another %c directive. If you want to use plain, unformatted log content, you need to pass an empty string for %c. Note that the parameters supplied to the % c directive and other alternative strings need to be added in the correct order. 😉
Group print & Print execution path
We’re just getting started. We’ve already introduced CSS styles to logging. What are the other secrets of Console?
Grouping print
Too much console logging is not a good idea, and it can lead to poor readability, resulting in log output that doesn’t make much sense. So, it’s always good to output structured logs.
You can do this using console.group(). By using this method, you can output deep collapsible structures (groups) in the console, which can better organize your log output. If you want to collapse your groups by default, there is also a console.groupcollapsed () method. Of course, nested groups can also be nested according to your needs. You can also give your group a log-like header form by passing it a list of arguments (as with console.log()). When using the group method, each console will find its location in the created group. You can use the console.groupend () method to close a group.
console.group();
console.log("Inside 1st group");
console.group();
console.log("Inside 2nd group");
console.groupEnd();
console.groupEnd();
console.log("Outer scope");
Copy the code
I think you’ve noticed that you can copy and paste the code from all of the provided snippets into your console and try them out the way you want!
The console results are as follows:
Print the execution path
Another useful piece of information you can get from the Console API is the path of the current call (execution path/stack trace). Did you know that there is a list of links (such as function chains) that are executed, and when console.trace() is called, it gets its execution path, which is the method we’re talking about. This information is useful, whether to detect side effects or check code flow. Just copy the code below to your console to see the result.
console.trace("Logging the way down here!");
Copy the code
The console results are as follows:
Console.XXX
You’ve probably already seen some interesting approaches to the Console API. Next, we’ll talk about adding some additional information to the log. Let’s take a quick look at them.
Warning
Console.warn () has the same effect as console.log(), but it has a warning-like style effect. In most browsers, it appears as yellow text and prompts a warning sign ⚠. Also, by default, console.warning() prints the execution path so you can quickly find the source of the warning.
console.warn("This is a warning!");
Copy the code
Error
Like console.warn(), the console.error() method prints a message with an execution path, and the style of the message is special. It is usually red and has the error icon ❌ added. This will clearly inform the user that there is something wrong with the code. It’s worth noting here that the console.error() method simply prints a console message, which has no additional effects, such as stopping the code from executing (so you can throw an error here). This is a simple note, as many beginners may find this feature a bit confusing.
console.error("This is an error!");
Copy the code
Info & debug
There are two other ways to print messages to the log. Next up are console.info() and console.debug(). They don’t always print in a unique style — in some browsers it’s just an icon. In fact, these and previous methods are intended to make it easier to print some of your actions in different categories in the console. Depending on the browser, the developer user interface gives you the option to display specific types of logs, such as errors, debug messages, or general messages.
console.info("This is very informative!");
console.debug("Debugging a bug!");
Copy the code
Assert
There is even a special Console method that provides shortcuts to perform different print effects based on conditional judgments (assertions). It is the console. The assert (). Just like the standard console.log() method, it can take an infinite number of arguments, the difference being that the first one must be a Boolean assertion. If the assertion is true, nothing happens; otherwise, it writes all passed arguments to the console as error messages (same as the console.error() method).
console.assert(true."This won't be logged!");
console.assert(false."This will be logged!");
Copy the code
Then, after printing some messages, you might want to make your console message panel look cleaner. No problem! Simply use the console.clear() method to make all old printed logs disappear! This is such a useful feature that it even has its own buttons (and shortcuts) in the console interface of most browsers! 👍
console.clear()
Copy the code
timing
The Console API even provides a set of time-sequence-related methods ⌚. Using them, you can quickly perform performance tests on parts of your code. The API is simple and you can start with the console.time() method, which takes optional parameters as labels or identifiers for a given timer. The associated timer starts when this method is called. You can then use the console.timelog () and console.timeend () methods (with optional identification parameters) to record your time (in milliseconds) or terminate the corresponding timer.
console.time();
// code snippet 1
console.timeLog(); // default: [time] ms
// code snippet 2
console.timeEnd(); // default: [time] ms
1234
Copy the code
Of course, if you are doing some real benchmarking or Performance testing, it is recommended to use the Performance API specifically designed for that purpose.
count
If you have a lot of logs printed, but you don’t know how many times a given part of the code is executed? There is also an API — console.Count () method whose most basic function is to count how many times it is called. Of course, you can also pass an optional argument that provides a label for a given counter (default). You can reset the selected counter using the console.countreset () method.
console.count(); // default: 1
console.count(); // default: 2
console.count(); // default: 3
console.countReset();
console.count(); // default: 1
Copy the code
form
I think this is one of the most underrated features of the Console API (beyond the CSS styles mentioned earlier). The ability to print real sortable tables to the console is very useful when debugging and printing two-dimensional objects and arrays. Right! You can actually display a table in the console. As simple as using console.table() and passing a parameter (an object or array, if it’s a raw value it’s usually just printing a plain log), try the following code snippet to see the effect.
console.table([[0.1.2.3.4], [5.6.7.8.9]]);
Copy the code
Console ASCII art
Without ASCII Art, the console would not be this great! With image-to-ASCII modules (available on NPM), you can easily convert normal images to their ASCII counterparts! 🖼 In addition, this module provides a number of customizable Settings and options to create the desired output. Here is a simple example of using this library:
import imageToAscii from "image-to-ascii";
imageToAscii(
"https://d2vqpl3tx84ay5.cloudfront.net/500x/tumblr_lsus01g1ik1qies3uo1_400.png",
{
colored: false,
}, (err, converted) => {
console.log(err || converted);
});
Copy the code
Using the code above, you can create amazing JS logos just like they are in the console right now! 🤯
With CSS styles and some padding and background properties, you can also export the full image to the console! For example, you can use this feature by looking at the console.image module (also on NPM). However, I think ASCII is more fashionable. 💅
Modern Logs
As you can see, your logging and debugging processes don’t have to be so monochrome at all! There’s more to it than simple console.log(). Armed with the knowledge of this article, now you can choose! You can either use the traditional console.log() and the different structured formats provided by browsers, or you can use the above methods to add some freshness to the console.
I hope you enjoyed this article and that it taught you something new. In the meantime, you can share this article with others so anyone can have a colorful console 🌈, and you can leave your comments in the comments! Plus, you can follow me on Twitter or send me a newsletter on Facebook! Finally, thanks again for reading and see you in the next article! ✌