From 936f62b40facca81b990da48a4aa2aabe5f76690 Mon Sep 17 00:00:00 2001 From: emanuele Date: Tue, 21 Jan 2020 09:45:22 +0000 Subject: [PATCH] chore: moved logger inside a module instead of having it inside the process --- cli.js | 8 +++----- lib/bootstrap.js | 9 +++++---- lib/commands/external.js | 6 ++++-- lib/groups/advanced.js | 21 +++++++++++---------- lib/utils/compiler.js | 25 +++++++++++++------------ lib/utils/logger.js | 5 +++++ lib/utils/process-log.js | 8 +++++--- 7 files changed, 46 insertions(+), 36 deletions(-) create mode 100644 lib/utils/logger.js diff --git a/cli.js b/cli.js index 912c3fd5217..1c863315aa0 100755 --- a/cli.js +++ b/cli.js @@ -5,15 +5,13 @@ require('v8-compile-cache'); const importLocal = require('import-local'); +const logger = require('./lib/utils/logger'); // Prefer the local installation of webpack-cli if (importLocal(__filename)) { return; } process.title = 'webpack'; -process.cliLogger = require('webpack-log')({ - name: 'webpack', -}); const updateNotifier = require('update-notifier'); const packageJson = require('./package.json'); @@ -24,7 +22,7 @@ const notifier = updateNotifier({ }); if (notifier.update) { - process.cliLogger.info(`Update available: ${notifier.update.latest}`); + logger.info(`Update available: ${notifier.update.latest}`); } const semver = require('semver'); @@ -33,7 +31,7 @@ const version = packageJson.engines.node; if (!semver.satisfies(process.version, version)) { const rawVersion = version.replace(/[^\d\.]*/, ''); - process.cliLogger.error('webpack CLI requires at least Node v' + rawVersion + '. ' + 'You have ' + process.version + '.\n' + 'See https://webpack.js.org/ ' + 'for migration help and similar.'); + logger.error('webpack CLI requires at least Node v' + rawVersion + '. ' + 'You have ' + process.version + '.\n' + 'See https://webpack.js.org/ ' + 'for migration help and similar.'); process.exit(1); } diff --git a/lib/bootstrap.js b/lib/bootstrap.js index b0aa0fb020b..a18995bee1f 100644 --- a/lib/bootstrap.js +++ b/lib/bootstrap.js @@ -2,6 +2,7 @@ const WebpackCLI = require('./webpack-cli'); const { core, commands } = require('./utils/cli-flags'); const cmdArgs = require('command-line-args'); +const logger = require('./utils/logger'); require('./utils/process-log'); @@ -65,7 +66,7 @@ async function runCLI(cli, commandIsUsed) { args._unknown .filter(e => e) .forEach(unknown => { - process.cliLogger.warn('Unknown argument:', unknown); + logger.warn('Unknown argument:', unknown); }); } const result = await cli.run(args, core); @@ -74,7 +75,7 @@ async function runCLI(cli, commandIsUsed) { } } catch (err) { if (err.name === 'UNKNOWN_VALUE') { - process.cliLogger.error(`Parse Error (unknown argument): ${err.value}`); + logger.error(`Parse Error (unknown argument): ${err.value}`); return; } else if (err.name === 'ALREADY_SET') { const argsMap = {}; @@ -99,9 +100,9 @@ async function runCLI(cli, commandIsUsed) { await cli.run(args, core); process.stdout.write('\n'); - process.cliLogger.warn('Duplicate flags found, defaulting to last set value'); + logger.warn('Duplicate flags found, defaulting to last set value'); } else { - process.cliLogger.error(err); + logger.error(err); return; } } diff --git a/lib/commands/external.js b/lib/commands/external.js index ad55f2c1ae8..f26df2d4a6b 100644 --- a/lib/commands/external.js +++ b/lib/commands/external.js @@ -1,6 +1,8 @@ /* eslint-disable @typescript-eslint/explicit-function-return-type */ const { prompt } = require('inquirer'); const chalk = require('chalk'); +const logger = require('../utils/logger'); + class ExternalCommand { static async runCommand(command, args = []) { const cp = require('child_process'); @@ -13,7 +15,7 @@ class ExternalCommand { reject(error); }); - executedCommand.on('exit', code => { + executedCommand.on('exit', () => { resolve(); }); }); @@ -37,7 +39,7 @@ class ExternalCommand { const options = [isYarn ? 'add' : 'install', '-D', scopeName]; const commandToBeRun = `${packageManager} ${options.join(' ')}`; - process.cliLogger.error(`The command moved into a separate package: ${chalk.keyword('orange')(name)}\n`); + logger.error(`The command moved into a separate package: ${chalk.keyword('orange')(name)}\n`); const question = `Would you like to install ${name}? (That will run ${chalk.green(commandToBeRun)})`; const { installConfirm } = await prompt([ { diff --git a/lib/groups/advanced.js b/lib/groups/advanced.js index a15edeaa22f..18b69001e53 100644 --- a/lib/groups/advanced.js +++ b/lib/groups/advanced.js @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/explicit-function-return-type */ const GroupHelper = require('../utils/group-helper'); +const logger = require('../utils/logger'); class AdvancedGroup extends GroupHelper { constructor(options) { @@ -15,7 +16,7 @@ class AdvancedGroup extends GroupHelper { name = name.substring(0, p); } } catch (e) { - process.cliLogger.error('Invalid plugin arguments ' + name + ' (' + e + ').'); + logger.error('Invalid plugin arguments ' + name + ' (' + e + ').'); process.exit(-1); // eslint-disable-line } @@ -24,20 +25,20 @@ class AdvancedGroup extends GroupHelper { const resolve = require('enhanced-resolve'); path = resolve.sync(process.cwd(), name); } catch (e) { - process.cliLogger.error('Cannot resolve plugin ' + name + '.'); + logger.error('Cannot resolve plugin ' + name + '.'); process.exit(-1); // eslint-disable-line } let Plugin; try { Plugin = require(path); } catch (e) { - process.cliLogger.error('Cannot load plugin ' + name + '. (' + path + ')'); + logger.error('Cannot load plugin ' + name + '. (' + path + ')'); throw e; } try { return new Plugin(args); } catch (e) { - process.cliLogger.error('Cannot instantiate plugin ' + name + '. (' + path + ')'); + logger.error('Cannot instantiate plugin ' + name + '. (' + path + ')'); throw e; } } @@ -75,11 +76,11 @@ class AdvancedGroup extends GroupHelper { if (args.global) { const globalArrLen = args.global.length; if (!globalArrLen) { - process.cliLogger.warn('Argument to global flag is none'); + logger.warn('Argument to global flag is none'); return; } if (globalArrLen === 1) { - process.cliLogger.warn('Argument to global flag expected a key/value pair'); + logger.warn('Argument to global flag expected a key/value pair'); return; } @@ -92,12 +93,12 @@ class AdvancedGroup extends GroupHelper { const argVal = arg.substr(splitIdx + 1); const argKey = arg.substr(0, splitIdx); if (!argVal.length) { - process.cliLogger.warn(`Found unmatching value for global flag key '${argKey}'`); + logger.warn(`Found unmatching value for global flag key '${argKey}'`); return; } // eslint-disable-next-line no-prototype-builtins if (providePluginObject.hasOwnProperty(argKey)) { - process.cliLogger.warn(`Overriding key '${argKey}' for global flag`); + logger.warn(`Overriding key '${argKey}' for global flag`); } providePluginObject[argKey] = argVal; return; @@ -106,10 +107,10 @@ class AdvancedGroup extends GroupHelper { const nextArg = args.global[idx + 1]; // eslint-disable-next-line no-prototype-builtins if (providePluginObject.hasOwnProperty(arg)) { - process.cliLogger.warn(`Overriding key '${arg}' for global flag`); + logger.warn(`Overriding key '${arg}' for global flag`); } if (!nextArg) { - process.cliLogger.warn(`Found unmatching value for global flag key '${arg}'`); + logger.warn(`Found unmatching value for global flag key '${arg}'`); return; } providePluginObject[arg] = nextArg; diff --git a/lib/utils/compiler.js b/lib/utils/compiler.js index 4f6d388fe89..70e0f1ef16d 100644 --- a/lib/utils/compiler.js +++ b/lib/utils/compiler.js @@ -2,6 +2,7 @@ const webpack = require('webpack'); const chalk = require('chalk'); const Table = require('cli-table3'); +const logger = require('./logger'); function setUpHookForCompiler(compiler, outputOptions, options) { const { ProgressPlugin } = webpack; @@ -20,7 +21,7 @@ function setUpHookForCompiler(compiler, outputOptions, options) { } if (msg && tmpMsg != msg) { - process.cliLogger.info(percent + '% ' + msg); + logger.info(percent + '% ' + msg); } tmpMsg = msg; }; @@ -44,17 +45,17 @@ function setUpHookForCompiler(compiler, outputOptions, options) { if (outputOptions.watch) { compiler.hooks.watchRun.tap('WebpackInfo', compilation => { const compilationName = compilation.name ? compilation.name : ''; - process.cliLogger.info('Compilation ' + compilationName + ' starting…'); + logger.info('Compilation ' + compilationName + ' starting…'); }); } else { compiler.hooks.beforeRun.tap('WebpackInfo', compilation => { const compilationName = compilation.name ? compilation.name : ''; - process.cliLogger.info('Compilation ' + compilationName + ' starting…'); + logger.info('Compilation ' + compilationName + ' starting…'); }); } compiler.hooks.done.tap('WebpackInfo', compilation => { const compilationName = compilation.name ? compilation.name : ''; - process.cliLogger.info('Compilation ' + compilationName + ' finished'); + logger.info('Compilation ' + compilationName + ' finished'); }); } } @@ -117,22 +118,22 @@ function generateOutputForSingleCompilation(statsObj, statsErrors, processingMes process.stdout.write('\n\n'); if (warning.message) { - process.cliLogger.warn(warning.message); + logger.warn(warning.message); process.stdout.write('\n'); - process.cliLogger.warn(warning.stack); + logger.warn(warning.stack); return; } - process.cliLogger.warn(warning); + logger.warn(warning); }); process.stdout.write('\n'); } if (statsErrors) { statsErrors.forEach(err => { - if (err.loc) process.cliLogger.warn(err.loc); + if (err.loc) logger.warn(err.loc); if (err.name) { process.stdout.write('\n'); - process.cliLogger.error(err.name); + logger.error(err.name); } }); } @@ -150,7 +151,7 @@ function generateOutput(outputOptions, stats, statsErrors, processingMessageBuff generateOutputForSingleCompilation(statsObj, statsErrors, processingMessageBuffer); process.stdout.write('\n'); if (outputOptions.watch) { - process.cliLogger.info('watching files for updates...'); + logger.info('watching files for updates...'); } } @@ -163,7 +164,7 @@ function compilerCallback(compiler, err, stats, lastHash, options, outputOptions } if (err) { lastHash = null; - process.cliLogger.error(err.stack || err); + logger.error(err.stack || err); process.exit(1); // eslint-disable-line } if (outputOptions.json && !outputOptions.silent) { @@ -213,7 +214,7 @@ async function webpackInstance(opts) { compiler = getCompiler(options); } catch (err) { process.stdout.write('\n'); - process.cliLogger.error(`${err.name}: ${err.message}`); + logger.error(`${err.name}: ${err.message}`); process.stdout.write('\n'); return; } diff --git a/lib/utils/logger.js b/lib/utils/logger.js new file mode 100644 index 00000000000..292e403a3a7 --- /dev/null +++ b/lib/utils/logger.js @@ -0,0 +1,5 @@ +const logger = require('webpack-log')({ + name: 'webpack', +}); + +module.exports = logger; diff --git a/lib/utils/process-log.js b/lib/utils/process-log.js index 57f885d2d99..204fa96e795 100644 --- a/lib/utils/process-log.js +++ b/lib/utils/process-log.js @@ -1,16 +1,18 @@ +const logger = require('./logger'); + /* eslint-disable @typescript-eslint/explicit-function-return-type */ function logErrorAndExit(error) { - if (error && error.stack) process.cliLogger.error(error.stack); + if (error && error.stack) logger.error(error.stack); process.exit(1); } process.on('uncaughtException', error => { - process.cliLogger.error(`Uncaught exception: ${error}`); + logger.error(`Uncaught exception: ${error}`); logErrorAndExit(error); }); process.on('unhandledRejection', error => { - process.cliLogger.error(`Promise rejection: ${error}`); + logger.error(`Promise rejection: ${error}`); logErrorAndExit(error); });