DEV Community

Discussion on: Better console.logs

Collapse
 
nblackburn profile image
Nathaniel Blackburn • Edited

I have gone about this via namespacing my debug logs so it assigns a colour based on that namespace.

debug('cache:set', {}) // cache:set +1ms {}

The namespace here being cache which is mapped against an array of colours using the following code...

let log = 'cache:set';
let colors = [];

const hash = data => {
    let hash = 0;

    for (let index = 0; index < data.length; index++) {
        hash = ((hash << 5) + hash + data.charCodeAt(index)) & 0xffffffff;
    }

    return hash;
};

let namespace = log.substring(0, log.indexOf(':'));
let color = colors[Math.abs(hash(namespace)) % colors.length];

This way cache logs are always shown in the same colour allowing you to visually identify them.