简体   繁体   中英

How use a "commander" CLI flag to set the the "winston" logging level in a node library

Given this sample commander application:

// index.ts

// Config Winston:
winston.configure({
    level: 'info',
    format: winston.format.combine(winston.format.splat(), winston.format.cli()),
    transports: [new winston.transports.Console({})],
});

winston.info('Started CLI')

// Configure commander
const cli = new Command()
    .option('--debug', 'Debug mode', false) // Or --verbose, it doesn't really matter.
    .action(actionCallback); // Imported.

cli.parse();

How can I set the winston logging level given the provided commander's option --debug ?

I could use a DEBUG env var, but that kinda breaks the purpose of the --debug flag in the CLI. Any suggestion?

The easiest solution, actually workaround, is to check for the --debug flag myself:

const debugLevel = process.argv.indexOf('--debug') != -1 ? 'debug' : 'info';

winston.configure({
    level: debugLevel,
    format: winston.format.combine(winston.format.splat(), winston.format.cli()),
    transports: [new winston.transports.Console({})],
});

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