3

So I want to disable logging for some of the environments for my Node.JS application (Express); is the following the best way to disable logging in Node.JS applications?

if(process.env.NODE_ENV == "production")
{
    console.log = function(){}; 
}

Does adding this piece of code in my app.js affect all the middle-wares and routes as well (I want to disable logging for whole application, routes, middle-wares,...)?

Thanks

2
  • usually production is where you want logs... i'm not sure if overriding console.log will take effect in modules but it should be easy to try it and find out. Also you might want to take a look at winston and conditionally activate/deactivate the loggers based on an env flag Commented Mar 30, 2015 at 15:26
  • That's just an example you can set it to any environment you wish... Commented Mar 30, 2015 at 18:09

1 Answer 1

8

You might want to move away from console.log and use a logging library such as winston, but it depends on how big your project is and how much flexibility you want.

By the way console.log = function() {}; will work, it just depends on whether you want some logging to work (as probably is the case, you might want to see errors) or not.

I've tested the previous by creating the following setup:

file 1.js

console.log = function() {};
require('./2');

file 2.js

// you will not see anything
console.log(2);

If you will decide to use it you will then be able to set logging levels , which will help you to not show verbose logs in a production environment.

For example:

var winston = require('winston');
winston.level = process.env.NODE_ENV == 'production' ? 'error' : 'debug';

// will show 'ERROR' in production logs
winston.error('ERROR') 

// will show 'called test function' in an environment
// different from production
winston.debug('called test function') 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.