DEV Community

Cover image for Extend console's methods without losing line information
Maxime Bouveron
Maxime Bouveron

Posted on

Extend console's methods without losing line information

Get ready for the most needlessly precise and niche post of this website as today we're learning how to add a colored chip in front of your browser's console logs!

Extending console's log, error, warn or other methods can be very useful to easily add some information or context to each log, especially using CSS styling!

There's lots of ways we can use that but in this example we'll focus on how to easily identify logs coming from a library.

You'll need to actually replace the method by a new one, I recommend doing so in your app entry point (index.js in my case)

const stylesWarning = [
    'background: #FFC82C',
    'border-radius: 3px',
    'color: white',
    'font-weight: bold',
    'padding: 2px 5px'
].join(';')

const _warn = console.warn;

console.warn = function(warnMessage) {
  console.group("%cMyLibrary", stylesWarning)
  _warn.apply(console, arguments)
  console.groupEnd()
}

You can then use the method as you would usually :

Console.warn call

Which will result in this :

Console.warn result

Convenient and pretty!

There's one problem though: the log's file and line number doesn't represent our original log but where our method was rewritten. (index.js instead of App.jsx in this case) Not that convenient.

Thankfully, there's a trick around that one: instead of replacing it with a new function, you need to modify the log method itself and return it. (Thank you StackOverflow's kylehuff!)

console.warn = function() {
  return Function.prototype.bind.call(_warn, console, "%cMyLibrary", stylesWarning);
}();

Which will result in something similar to the previous one (I actually find it prettier) except for the line number showing the actual file and line number.

Console.warn result

If you or anyone in your team use VSCode's debugger, there's a little trick : CSS styles aren't reset between each argument so you'll need to add a second "%c" and a meaningless CSS rule string if you don't want your whole line colored, like so:

console.warn = function() {
  return Function.prototype.bind.call(_warn, console, "%cMyLibrary%c", stylesWarning, 'color: inherit');
}();

The result is pretty useful and you won't have to change any of your console calls. If you can tough, I recommend writing your own logger helper without mutating the console object, it'll be less risky but you'll have to refactor a lot of code.

What do you think? Do you use this kind of tricks in your projects? Don't hesitate to comment!

Latest comments (1)

Collapse
 
bgord profile image
Bartosz Gordon

Great trick!

"Millions of families suffer every year!"