Search code examples
gitnode.jsdebuggingproduction-environmentconsole.log

Right way to push to production without console and debug statements in node.js?


I'm new to node.js - is there a way to git push to say my Heroku production environment in a way that remove console.log statements? Or is it okay to leave them in?

What's the right way to handle local code full of debugging statements, without losing the statements but without pushing them to production.

I'm developing locally.

Thanks for your expertise.


Solution

  • I create a log helper file. I then use a debugMode field in my config.json or environment variables, and use nconf npm to read from this.

    The below is an example of the log.coffee file

    ##
    # * console logging for the application
    
    nconf = require('nconf')
    nconf.argv().env().file file: "./config.json"
    
    ##
    # log - log information to the console 
    #   params:
    #     code - DEBUG, ERROR, WARNING, INFO
    #     message - the log message to display
    #     data - optional data info
    #   returns: nothing
    module.exports.log = (code, message, data) ->
      if nconf.get('DEBUG_MODE') == 'true' || nconf.get('DEBUG_MODE') == true
        if data?
          # if the data is an object, stringify it for output
          if typeof data == 'object'
            data = JSON.stringify(data)
    
          console.log code.toUpperCase() + ': ' + message
          console.log code.toUpperCase() + ': ' + '(continued) ' + data
        else
          console.log code.toUpperCase() + ': ' + message
    

    Then in any file that I want to log, I simply include this file and log to it, rather than using console.log everywhere.

    sample.coffee

    logger = require('../log')
    
    module.exports.getEvent = (eventDb) ->
      logger.log 'debug', '/server/adapters/event/getEvent called', eventDb
    

    The logger allows for a severity code, message, and optionally data that will show up in the terminal, and if you are not in debug mode, it will simply not do anything.