Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement firebug's console.table in chrome

I'm logging various performance metrics to the console (if present). This content is best viewed as a table, and FireBug's console.table() method works great--but most of my users are in Chrome.

console.table() is a great solution, because I get a well-formatted UI styled grid without needing to build and maintain a dedicated UI control. Currently, in Chrome, I can only log unformatted text.

Alternatively, if there is a way to render HTML content in the console, that would work too. I can send html to the console, but it renders as DOM content does in the elements tab. I know the inspector is just HTML/JS/CSS--so it's technically possible. In fact, I can do it when I inspect the inspector--but this doesn't solve the problem for the real world.

like image 351
Christopher Avatar asked Jun 14 '12 04:06

Christopher


Video Answer


2 Answers

Now you can do it in Chrome Canary https://plus.google.com/+GoogleChromeDevelopers/posts/j8dMDxqbVv7

like image 159
MauroPorras Avatar answered Oct 29 '22 23:10

MauroPorras


I had the same problem and wrote the code below. It isn't as fully featured as console.table, it only accepts an array of records, and doesn't take a list of columns. The output also isn't as nice, but it was enough for me. An example:

$ console_table([{who:"World",message:"Hello"}
                ,{who:"My wife",message:"Good Morning!"}])
|who    |message      |
|World  |Hello        |
|My wife|Good Morning!|

And the code behind it:

// Will be available in the latest Chrome, then I can delete this
function console_table(xs)
{
    if (xs.length === 0)
        console.log("No data");
    else
    {
        var widths = [];
        var cells = [];
        for (var i = 0; i <= xs.length; i++)
            cells.push([]);
        for (var s in xs[0])
        {
            var len = s.length;
            cells[0].push(s);
            for (var i = 0; i < xs.length; i++)
            {
                var ss = "" + xs[i][s];
                len = Math.max(len, ss.length);
                cells[i+1].push(ss);
            }
            widths.push(len);
        }
        var s = "";
        for (var x = 0; x < cells.length; x++)
        {
            for (var y = 0; y < widths.length; y++)
                s += "|" + pad(widths[y], cells[x][y]);
            s += "|\n";
        }
        console.log(s);
    }
}

function pad(n,s)
{
    var res = s;
    for (var i = s.length; i < n; i++)
        res += " ";
    return res;
}
like image 36
Neil Mitchell Avatar answered Oct 30 '22 00:10

Neil Mitchell