Colouring console.log() with a JavaScript proxy object

Are you the sort of web developer who uses console.log() to log out the flow through your code, confirming it’s following the paths you expect. Do you end up with liberal sprinklings of console.log() calls, each with a prefix or identifier to show its context? If that’s you, wouldn’t you love to have the console equivalent of some coloured sticky tabs to quickly let you focus on key logs while being able to ignore all the other messages you’ve spattered around? Wouldn’t it be great to have, and even console.log.rebeccapurple() ? Just drop this bit of code into your website and you can do exactly that:

console.log = new Proxy(console.log, {
  get(obj, prop) {
    return (...params) => console.log('%c ', `border-left: 5px solid ${prop}`, ...params);

The output looks like this (Firefox on Linux):

Screenshot of extended console.log() use in Firefox

You can actually use any CSS colour name for the last part of the call. And it doesn’t care about case, either. Green, lightBlue, OLIVE and GoldenRod will all work, to name but a few. Plain old console.log() still works, too. It’s a quick and easy way to draw attention to specific log lines amongst a sea of output.

It works by using a JavaScript proxy object to intercept any calls to console.log.WHATEVER(). It pulls out the “WHATEVER” and puts it into a little bit of CSS which adds a thick border to a single space character at the start of some normal console.log() output. Any other parameters are appended to the call, inspecting arrays and objects still works. If “WHATEVER” isn’t a valid CSS colour name you still get the output, but with a blank border at the left.

The code above is fairly readable, but if you want to condense it down into as few characters as possible, here’s a more Twitterable version of the same thing:

c=console;c.log=new Proxy(c.log,{get(_,p){return(...a)=>c.log('%c ', `border-left: 5px solid ${p}`, ...a)}});

You can also play around with the CSS for different effects. A small coloured flag at the left of the line suits my tastes, but perhaps you want a thinner border, or a thicker one – or maybe you want to colour the background or the text itself.

This trick is a simple one to pull off, but opens up many other possibilities. In the next few posts I’ll look at how I’ve extended this approach to provide me with a few custom logging options to make my life as developer a little easier.

Leave a Reply

Your email address will not be published. Required fields are marked *