0

This question is similar in nature to Converting an object to a string

console.log works awfully good. It can log very deep objects, self-referencing objects, nulls, undefined, multiparams...

How can I store the output of the function as a string? I want to have my own logging system, but I want to keep the same format as console.log.

The most voted answer for the referenced question does not work with self referencing objects. Nor does .toString():

> a = {}
{}
> a.b = a
<ref *1> { b: [Circular *1] }
> a
<ref *1> { b: [Circular *1] }
> a.b
<ref *1> { b: [Circular *1] }
> JSON.stringify(a)
Uncaught TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    --- property 'b' closes the circle
    at JSON.stringify (<anonymous>)
> console.log(a)
<ref *1> { b: [Circular *1] }
undefined
> a.toString()
'[object Object]'

Basically I would want some function stringify with

> stringify(a) === '<ref *1> { b: [Circular *1] }'

The question is also similar to How can I print a circular structure in a JSON-like format? but not exactly. The question there is to log one self referencing object. I'm asking for something more generic, which is something like the console output. In particular, console handles gracefully multiparams

Gabriel Furstenheim
  • 2,969
  • 30
  • 27
  • The problem there is that you need to stringify something that'll lead to infinite recursion. You could take a look at the answers [here](https://stackoverflow.com/questions/11616630/how-can-i-print-a-circular-structure-in-a-json-like-format), or just use [a library](https://github.com/WebReflection/circular-json) that already solved this problem. – Cerbrus Sep 17 '21 at 11:35
  • I don't think it is possible. What is in the console cannot be accessed by a script. – Đinh Carabus Sep 17 '21 at 11:35
  • @ĐinhCarabus: _"I want to have my own logging system"_ The OP is writing his own logging system. – Cerbrus Sep 17 '21 at 11:37
  • @Cerbrus, yes, but OP wants to use the exact output that `console.log` produces, which isn't accessible (OP: *"How can I store the output of the function as a string?"*). – Đinh Carabus Sep 17 '21 at 11:38
  • Well console.log.bind works in some browsers but you need your own functions work properly –  Sep 17 '21 at 11:40
  • @ĐinhCarabus: That can be faked, up to a point. The OP wants to stringify objects in a console-like format. That's far from impossible, – Cerbrus Sep 17 '21 at 11:41
  • @Cerbrus, of course. My point is that it is impossible to do this by using `console.log` internally. – Đinh Carabus Sep 17 '21 at 11:46
  • Your comment seems to say that the whole question is impossible, @ĐinhCarabus. – Cerbrus Sep 17 '21 at 11:47
  • @Cerbrus You're right. I should have made this more clear. – Đinh Carabus Sep 17 '21 at 11:59

0 Answers0