05 July 2021

A console.log decorator in JavaScript

Here’s a quick way to wrap a javascript function with a decorator so every time you call it, it initiates a console.group(…) or console.groupCollapsed(…). Console.group is a built-in way to group a series of console.log calls under a bold label, in a collapsible group.

This decorator will also automatically close the group (via console.groupEnd) when the function terminates, be it:

  • synchronously
  • thrown error
  • resolved promise
  • rejected promise

This means any calls to console.log that happen during the execution of the wrapped function will be neatly grouped together in your console!

It’s called groupFn:

TypeScript definitions in the gist!

A simple example:

const doThing = groupFn("Doing thing", (index) => {
  console.log(`in Function: ${index}`);
  return Promise.resolve().then(() => {
    console.log(`in Promise: ${index}`);
    return true;

doThing(1).then(() => doThing(2));

Which outputs:

output of code snippet

The example shows it working with promises that run in serial, if you use this with promises that are running in parallel or with recursion, then it’s possible for the grouping to get mixed up and start nesting.

This can be a great way to audit some complicated execution in an app, but if you’re using it in code that ships to a production website, then you’ll probably want to add in a way to disable or bypass the logging there.

Another useful way to break up console.log statements, which I’ll leave as an exercise to the reader is by applying CSS styling (e.g., colors, font-size, font-style, etc.) using the %c directive.

Did you find this helpful or fun? paypal.me/mrcoles
comments powered by Disqus

Peter Coles

Peter Coles

is a software engineer living in NYC who is building Superset 💪 and also created GoFullPage 📸
more »

github · soundcloud · @lethys · rss