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' };
log.info(err);
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 ):
https://github.com/enonic/lib-util/blob/master/src/main/resources/site/lib/enonic/util/util.js

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 - http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax):

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

So, to log info you can use the following:

log.info('My message');
log.info('My message with param %s', 4);
log.info('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):

log.info('My JSON %s', JSON.stringify(json, null, 4));

Or using our buildt-in JSON converter:

log.info('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 log.info('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 log.info('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') {
      log.info(JSON.stringify(json, null, 4));
   }
   ....
}

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