How to log based on environment


This post goes over how to log based on environment in Node.js.

Environment Variable

To log in development, check NODE_ENV before logging information:

if (process.env.NODE_ENV === 'development') {
  console.log('...');
}

Alternatively, to log everywhere except production:

if (process.env.NODE_ENV !== 'production') {
  console.log('...');
}

Make sure to set the environment variable before running the app or script:

NODE_ENV=development

debug

debug can toggle the output based on the DEBUG environment variable.

First install debug:

npm install debug

Then create a debug function named myapp:

const debug = require('debug')('myapp');

Call debug with data:

debug('...');

Enable debug logs by setting the DEBUG environment variable with the name myapp:

DEBUG=myapp

Or enable all debug output with *:

DEBUG=*

See the repository for more details.



Please support this site and join our Discord!