I'm currently developing a node js cli tool to do some random stuff for work. Up until this point, my whole app was designed as a cli without any intention to use its functionality somewhere else.
Now some of my collegues like to work with a ui instead of a cli so I decited to build a vue web app around it. SO far so good.
Now my problem: I plastered all of my functions with console.logs and packages like cliui, chalk, inquirer, etc. This obviously makes no sense when used as a module in a vue app.
My question is: How do I log output from individual functions only when used via cli?
One idea I have is to set some kind of falgg in my command function so the process knows I'm in a terminal and check for every console.log if that flag is set. But that seems to be a lot of work and I wonder if there is a better way.
CodePudding user response:
I would strongly suggest to use some logging library, like for instance winston. There you can define multiple so called transports, which are responsible for writing the logs in the respective specified location (for instance a file, a database or just the console). Then do all your logging only through this library.
So you will have a single point in the very beginning of your app, where you can define whether to activate a transport to the console or not ...
CodePudding user response:
One solution could be to use something like Winston as your logger. This could be a very simple and quick 'search and replace' for replacing 'console' with 'winston'. When you start the application, set the log level and you're set
const winston = require('winston');
winston.level = 'debug';
winston.log('debug', 'default logger being used');
CodePudding user response:
I'm not versed in NodeJS that well, but what I can suggest is "guard clauses" in each method that has CLI outputs and some sort of isCLI
boolean flag as an optional parameter to manipulate that clause.
That could be ugly, so another approach would be to separate out the CLI outputs and have a --verbose
flag or the likes for your CLI for when you want to see said outputs