Serialize js-objects in JS logging functions

When I log a JS object through the log methods, the object gets serialized to [object Object]. This is never what you want, really - what you DO want is the serialized version (JSON-style).

That is - instead of:

var err = { error: 'such hard to debug' };
log.error(JSON.stringify(err, null, '  '));

, I could simpy do:

var err = { error: 'wow eazi' };;
1 Like

Yes, we are aware of this - should probably be a core function?

I assume you are aware of the util library… It has a simple wrapper function called util.log( err ):

Yep I know - but why have a utility for logging when there’s a “native” logging function that does the same? Also, there’s no control over info vs warning vs error etc with the util lib.

The logging functions follows the following pattern (using string format -

log.<level>(<msg>, <args..>);

So, to log info you can use the following:'My message');'My message with param %s', 4);'My %s with param %s', 'message', 4);

When trying to log JSON objects you can either do it like this (using 4 spaces as indent):'My JSON %s', JSON.stringify(json, null, 4));

Or using our buildt-in JSON converter:'My JSON %s', json);

If you use this as the first parameter (message), then it will just do a toSting()on the parameter.

So, no need for the util in the previous post.

Hope that helps.

Will this last example take any javascript object and print it as JSON?

How do you use the built-in json converter? I tried the'My JSON %s', json); with a component and what I got was not very human readable:

My JSON {"name":"Post single","path":"main/0/left/0","type":"part","descriptor":"com.enonic.theme.superhero:post-single","config":{}}

It’s kind of a pain to write'My JSON %s', JSON.stringify(json, null, 4));

How about log.json(object, level); The “level” param would be “info”, “warning”, “error” etc.

It’s printed out as JSON without indention. It’s a lot of variations here and I do not think one solution fits all. The good thing here is that you can always create your own.

exports.json = function(object, level) {
   if (level === 'info') {, null, 4));

Yes, any javascrip object and print it as JSON. Arrays, Objects, functions.