node.jsloggingcommand-line-interfacewinstonnode-commander

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?


Solution

  • 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({})],
    });