adamschwartz / log

Console.log with style.
https://adamschwartz.co/log
MIT License
3.01k stars 140 forks source link

Colorize an object #41

Closed W-prog closed 7 years ago

W-prog commented 7 years ago

Hello,

How it's possible to colorize an object's log ? I've try console.log($scope.myObject); to log('[c="color: #32c5d2"]' + $scope.myObject + '[c]'); The line is colorize but I can't click on the object for inspecting the properties

adamschwartz commented 7 years ago

The issue is that attempting to concatenate your object is causing it to be .toString()d before log even has a chance to work on it. In Chrome if you log an object, you already get colored syntax highlighting though.

image

The best you could achieve if you wanted to log your object pretty printed and syntax highlighted (with different colors than Chrome devtools already provides) would be to use JSON.stringify, run your own syntax highlighting on the string, and then log it yourself. For example, you could modify this SO answer to use the custom syntax you mentioned above rather than the <span> output:

function syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

Source: http://stackoverflow.com/a/7220510/131898