Wrap a console.log with infinite optional params

Viewed 1089

I'm trying to create a custom logger which just wraps a console.log but always adds something to the start which makes it absolutely clear that the log is coming from my plugin.

I have come up with the following code:

var log = function(param1, param2) {
    if (typeof param3 !== 'undefined') {
        console.log('[MyPlugin]', param1, param2, param3);
    } else if (typeof param2 !== 'undefined') {
        console.log('[MyPlugin]', param1, param2);
    }
};

This allows the developer to run the following:

log('foo', 'bar');
// Outputs '[MyPlugin] foo bar'

log('foo');
// Outputs '[MyPlugin] foo'

But I hope that this can be improved upon.

The issues with this implementation are:

  1. The logging function only allows two parameters. It would be better if it could accept many.
  2. There's lots of repetition (multiple console.log calls).

What I have tried.

I thought maybe the ES6 spread-operator would work:

var log = function(...params) {
    console.log('[MyPlugin]', params);
};

Which allows the developer to run:

log('foo', 'bar');
// Outputs '[MyPlugin] Array [ "foo", "bar" ]'

log('foo');
// Outputs '[MyPlugin] Array [ "foo" ]'

You can see that the output is not the same as in the original function.

Is there a better solution?

1 Answers
Related