Pass multiple arguments to console.log from another javascript function

One thing we learned from our last project is that console.log can generate a LOT of noise. This noise is OK from a development environment, but once we move into production, it doesn’t make sense to still be writing to the log… that is until something goes horribly wrong in production and we need it enabled again!

For the record, nothing went horribly wrong in production.

So I devised a small helper class that will show or hide console.log messages depending on how you initialize it. The tricky part is that console.log can take multiple parameters, so I had to use console.log.apply(console, arguments); to relay those parameters untouched.

// logging utility library
function Log(_logConsole) {
	var self = this;
	this.logConsole = true;
	this.log = function() {
		if (self.logConsole) {
			console.log.apply(console, arguments);
		}
	};
	this.init = function () {
		if (_logConsole !== undefined) {
			self.logConsole = _logConsole;
		}
	};
	self.init();
}

And invoke it with:

var jsLog = new Log(true); // write to console
jsLog.log('Loading data', data, this);

Leave a Reply

Your email address will not be published. Required fields are marked *