0

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?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335
  • 2
    Did you try to research this before asking your question? A Google Search for "logging in nodejs" yields [this](https://blog.risingstack.com/node-js-logging-tutorial/) as the first search result, which contains a number of relevant strategies. – Robert Harvey Mar 14 '18 at 15:59
  • 1
    [Google](https://www.google.co.uk/search?q=node.js+log+library&oq=node.js+log+library&aqs=chrome..69i57j0.280j0j7&sourceid=chrome&ie=UTF-8) [turns](https://blog.risingstack.com/node-js-logging-tutorial/) [up](https://github.com/winstonjs/winston) [interesting](https://www.loggly.com/blog/node-js-libraries-make-sophisticated-logging-simpler/) [results](https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/) – Quentin Mar 14 '18 at 15:59
  • I'm kind of surprised this is a question for an ecosystem as rich as nodejs. – rmlan Mar 14 '18 at 15:59
  • have you tried using [winston](https://github.com/winstonjs/winston)? – Ritik Saxena Mar 14 '18 at 16:00
  • 1
    @RitikSaxena: Winston is mentioned in the article I linked. – Robert Harvey Mar 14 '18 at 16:00
  • I initially wanted to implement basic logging functionality from scratch so my bad I didn't guess to find an existing solution. – Sergei Basharov Mar 14 '18 at 16:40

3 Answers3

1

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

Ricardo Costa
  • 704
  • 6
  • 27
0

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

abhinav pandey
  • 574
  • 2
  • 8
  • 21
0

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.

PrivateOmega
  • 2,509
  • 1
  • 17
  • 27