Reputation: 14934
Currently I'm having a lot of console.log
in my modules. Many of them are debug-messages, which I only need to see, if I'm debugging my application.
I would like to enable debugging using a parameter when starting up my application, for instance node myApp.js -d
. Further my module should then only call the console.log
if debugging is active.
What is best practice in Node to accomplish this?
Upvotes: 4
Views: 2514
Reputation: 4376
Look up npm debug. I believe that's what you are looking for.
To Install debug:
npm install debug --save
example code:
var debug = require('debug')('your module');
debug('msg', 'more details');
To start debugging all the application run the following:
DEBUG=* node myApp.js
To debug only a few modules on your app:
DEBUG=first,second node myApp.js
For no debugging run your app normally
node myApp.js
Upvotes: 4
Reputation: 3977
Use something like winston , as it provides different logging options. Below is a simple example of something u may need
// Require winston logging library
var winston = require('winston');
// Check if -d is present as CLI argument
if(process.argv.indexOf('-d') > -1){
winston.level = 'debug';
}
// This is only print when winston.level is debug
winston.log('debug', 'Now my debug messages are written to console!');
Upvotes: 3