2

How can we format a value into a string to be consistent with how console.log(value) does it?

I need to append extra details to each value I am printing, without breaking the default formatting provided by console.log. It is easy for simple values, but for such types as Date and Object it is more complicated.

Is there a way I can make it consistent with console.log? In other words, how to format a value to be the same string as we get from console.log(value)?


I'm trying to implement a simple library manakin. Here's its complete source code:

'use strict';

(function () {

    var error = console.error, warn = console.warn;

    console.error = function () {
        var a = arguments;
        error.apply(this, Object.keys(a).map(function (key) {
            return "\u001b[31m" + a[key] + "\u001b[0m";
        }));
    };

    console.warn = function () {
        var a = arguments;
        warn.apply(this, Object.keys(a).map(function (key) {
            return "\u001b[33m" + a[key] + "\u001b[0m";
        }));
    };

})();

The problem I am having is that for types Date and Object the output is different:

// without manakin:
console.warn({value: 1});
//=> { value: 1 }

// with manakin:
console.warn({value: 1});
//=> [object Object]

And I want to make it consistent.


SOLVED

In the end I figured out how to make it all work in both both Node.js and in all browsers, see manakin source code (it is small).

It required different implementation for Node.js and for the browsers. Specifically under Node.js it uses util.inspect.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138

1 Answers1

1

I believe if you modify the code in warn to be:

console.warn = function () {
    var a = arguments;
    warn.apply(this, Object.keys(a).map(function (key) {
      if (a[key] instanceof Date) {
        return "\u001b[33m" + a[key].toString() + "\u001b[0m";
      }
      return "\u001b[33m" + JSON.stringify(a[key]) + "\u001b[0m";
    }));
};

you have what you're looking for. I tested it out by just pasting the new code in the console and logging the examples you have, hope that works for you!

omarjmh
  • 13,632
  • 6
  • 34
  • 42
  • 1
    I thought this approach too, but for dates, `JSON.stringify` returns them in RFC3339 format, while `console.log` prints them in what seems to be RFC1123. Maybe checking for `a[key] instanceof Date` and, if true, use `a[key].toString()` instead. – noisypixy Jun 19 '16 at 23:41
  • But the output from `JSON.stringify` is still very different from `console.log` formatting. – vitaly-t Jun 19 '16 at 23:51
  • 1
    I think I will make it for Node.js only, and then use this: http://stackoverflow.com/questions/10729276/how-can-i-get-the-full-object-in-node-js-console-log-rather-than-object. Because otherwise there seems to be no way to provide consistent formatting. – vitaly-t Jun 19 '16 at 23:57
  • In the end I got it all working everywhere - see the update ;) – vitaly-t Jun 20 '16 at 02:45