简体   繁体   中英

How to enable debugging in Node.js application

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?

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!');

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM