Sergei Basharov
Sergei Basharov

Reputation: 53830

How to implement logging in a console app?

Right now I put console.log(something) where I want to see what's happening in those places where I put it. When I see it's fine, I remove it.

How do I better implement logging functionality which I can easily turn on/off, e.g. with a start command line parameter node app.js debug=true?

Upvotes: 0

Views: 89

Answers (3)

PrivateOmega
PrivateOmega

Reputation: 2880

Easiest you could do is use Winston or any similar node packages

Add this code as a logger-service and wrap it in a function

const logger = winston.createLogger({
    transports: [
        new winston.transports.Console()
    ]
});

Require this logger service's function and log using any of the below formats.

logger.log({
  level: 'info',
  message: 'Hello distributed log files!'
});

logger.info('Hello again distributed logs');

Hope this helps.

Upvotes: 0

abhinav pandey
abhinav pandey

Reputation: 584

Your problem can be solved by using different logging levels. Ideally the log statements that you delete after development can be assigned to DEBUG level. So they will output only when the app is running in debug mode.

Most 3rd party loggers support this. You can check out Winston

Upvotes: 0

Ricardo Costa
Ricardo Costa

Reputation: 729

you can do it like this:

somewhere in your code:

const debug = true

then:

    if(debug){
      console.log(yourvar)
    }

or like someone suggested:

function debugMe(debug, yourvar){
  if(debug){
    console.log(yourvar)
  }
}

wrap it in a function

Upvotes: 1

Related Questions