December 2, 2017

Simple Logger Module to hide console.log in production

Logging can be very useful for debugging, but is something generally not desired while running in production. There's a number of ways to automate this, and this article displays how to build a simple module that wraps console statements and only displays logs while in development.

This module needs to:

  1. Provide a familiar interface to that of console.log, if not idential
  2. Retain line numbers and other console.x features
  3. Automatically hide logs in production

Here's what you need:

First off, (as in most React setups), an environment variable is setup on build:

Package.json
"scripts": {
    "start": "NODE_ENV=development webpack....
...
}

The module itself wraps console.log, correctly binding to its context and exposes itself as a singleton. (This is an example of a time it is good to use a singleton):

Logger.js
const DEBUG = process.env.NODE_ENV === 'development';

class Logger {
  log = DEBUG ? console.log.bind(window.console) : () => {};
}

export default new Logger();

Finally, the component that can import and use the logger as needed:

Component.js
import Logger from './logger';

Logger.log('this will only log in development environments');

This can be enhanced by wrapping debug and info methods as well, or even adding a way to send the logs to the backend.