From 9c613902c22681a4ad28d617a911203df817b951 Mon Sep 17 00:00:00 2001 From: ULIVZ <472590061@qq.com> Date: Sun, 25 Nov 2018 21:30:59 +0800 Subject: [PATCH] feat($core): more concise logger --- packages/@vuepress/core/lib/build.js | 4 +- packages/@vuepress/core/lib/dev.js | 2 +- .../@vuepress/core/lib/plugin-api/index.js | 14 ++- .../@vuepress/core/lib/prepare/AppContext.js | 6 +- .../@vuepress/core/lib/prepare/CacheLoader.js | 4 +- .../@vuepress/core/lib/prepare/loadTheme.js | 4 +- .../core/lib/webpack/DevLogPlugin.js | 2 +- .../core/lib/webpack/createBaseConfig.js | 2 +- packages/@vuepress/plugin-pwa/index.js | 2 +- packages/@vuepress/shared-utils/lib/logger.js | 116 +++++++++++------- 10 files changed, 92 insertions(+), 64 deletions(-) diff --git a/packages/@vuepress/core/lib/build.js b/packages/@vuepress/core/lib/build.js index b9a00a95be..e923555e88 100644 --- a/packages/@vuepress/core/lib/build.js +++ b/packages/@vuepress/core/lib/build.js @@ -15,7 +15,7 @@ module.exports = async function build (sourceDir, cliOptions = {}) { const { createBundleRenderer } = require('vue-server-renderer') const { normalizeHeadTag, applyUserWebpackConfig } = require('./util/index') - logger.wait('\nExtracting site metadata...') + logger.wait('Extracting site metadata...') const ctx = await prepare(sourceDir, cliOptions, true /* isProd */) const { outDir, cwd } = ctx @@ -82,7 +82,7 @@ module.exports = async function build (sourceDir, cliOptions = {}) { // DONE. const relativeDir = path.relative(cwd, outDir) - logger.success(`\n${chalk.green('Success!')} Generated static files in ${chalk.cyan(relativeDir)}.\n`) + logger.success(`${chalk.green('Success!')} Generated static files in ${chalk.cyan(relativeDir)}.\n`) // --- helpers --- diff --git a/packages/@vuepress/core/lib/dev.js b/packages/@vuepress/core/lib/dev.js index f6cf46f084..09d92223fa 100644 --- a/packages/@vuepress/core/lib/dev.js +++ b/packages/@vuepress/core/lib/dev.js @@ -19,7 +19,7 @@ module.exports = async function dev (sourceDir, cliOptions = {}) { const { applyUserWebpackConfig } = require('./util/index') const { frontmatterEmitter } = require('@vuepress/markdown-loader') - logger.wait('\nExtracting site metadata...') + logger.wait('Extracting site metadata...') const ctx = await prepare(sourceDir, cliOptions, false /* isProd */) // setup watchers to update options and dynamically generated files diff --git a/packages/@vuepress/core/lib/plugin-api/index.js b/packages/@vuepress/core/lib/plugin-api/index.js index 88bd13636e..5cc7f9f2fd 100644 --- a/packages/@vuepress/core/lib/plugin-api/index.js +++ b/packages/@vuepress/core/lib/plugin-api/index.js @@ -62,7 +62,7 @@ module.exports = class PluginAPI { if (plugin.enabled) { this.applyPlugin(plugin) } else { - logger.debug(`\n${chalk.gray(`[${plugin.name}]`)} disabled.`) + logger.debug(`${chalk.gray(`[${plugin.name}]`)} disabled.`) } }) } @@ -98,7 +98,7 @@ module.exports = class PluginAPI { this._pluginQueue.push(plugin) if (plugin.plugins) { - logger.debug(`\nStart to use plugins defined at ${chalk.gray(plugin.name)}`) + logger.debug(`Start to use plugins defined at ${chalk.gray(plugin.name)}`) logger.debug(JSON.stringify(plugin.plugins, null, 2)) this.useByPluginsConfig(plugin.plugins) } @@ -211,10 +211,12 @@ module.exports = class PluginAPI { alias }) { const isInternalPlugin = pluginName.startsWith('@vuepress/internal-') - if (shortcut) { - logger.tip(`\nApply plugin ${chalk.magenta(shortcut)} ${chalk.gray(`(i.e. "${pluginName}")`)} ...`) - } else if (!isInternalPlugin || isDebug) { - logger.tip(`\nApply plugin ${chalk.magenta(pluginName)} ...`) + if (isDebug && !isInternalPlugin) { + logger.tip( + shortcut + ? `Apply plugin ${chalk.magenta(shortcut)} ${chalk.gray(`(i.e. "${pluginName}")`)} ...` + : `Apply plugin ${chalk.magenta(pluginName)} ...` + ) } this diff --git a/packages/@vuepress/core/lib/prepare/AppContext.js b/packages/@vuepress/core/lib/prepare/AppContext.js index 67dbd89c69..d0b8e99e1f 100644 --- a/packages/@vuepress/core/lib/prepare/AppContext.js +++ b/packages/@vuepress/core/lib/prepare/AppContext.js @@ -229,8 +229,8 @@ module.exports = class AppContext { defaultDevTemplate ]) - logger.debug('\nSSR Template File: ' + chalk.gray(ssrTemplate)) - logger.debug('\nDEV Template File: ' + chalk.gray(devTemplate)) + logger.debug('SSR Template File: ' + chalk.gray(ssrTemplate)) + logger.debug('DEV Template File: ' + chalk.gray(devTemplate)) this.devTemplate = devTemplate this.ssrTemplate = ssrTemplate } @@ -346,7 +346,7 @@ function createTemp (tempPath) { fs.emptyDirSync(tempPath) } - logger.tip(`\nTemp directory: ${chalk.gray(tempPath)}`) + logger.tip(`Temp directory: ${chalk.gray(tempPath)}`) const tempCache = new Map() async function writeTemp (file, content) { diff --git a/packages/@vuepress/core/lib/prepare/CacheLoader.js b/packages/@vuepress/core/lib/prepare/CacheLoader.js index a3c01825ff..7b611a3a19 100644 --- a/packages/@vuepress/core/lib/prepare/CacheLoader.js +++ b/packages/@vuepress/core/lib/prepare/CacheLoader.js @@ -54,8 +54,8 @@ exports.getCacheLoaderOptions = function (siteConfig, cliOptions, cwd, isProd) { ) }) - logger.debug('\nCache directory: ' + chalk.gray(cacheDirectory)) - logger.debug('\nCache identifier : ' + chalk.gray(cacheIdentifier)) + logger.debug('Cache directory: ' + chalk.gray(cacheDirectory)) + logger.debug('Cache identifier : ' + chalk.gray(cacheIdentifier)) return { cacheDirectory, cacheIdentifier } } diff --git a/packages/@vuepress/core/lib/prepare/loadTheme.js b/packages/@vuepress/core/lib/prepare/loadTheme.js index eccfeabe2d..207d344804 100644 --- a/packages/@vuepress/core/lib/prepare/loadTheme.js +++ b/packages/@vuepress/core/lib/prepare/loadTheme.js @@ -48,7 +48,7 @@ module.exports = async function loadTheme (ctx) { if (useLocalTheme) { themePath = localThemePath - logger.tip(`\nApply theme located at ${chalk.gray(themePath)}...`) + logger.tip(`Apply theme located at ${chalk.gray(themePath)}...`) } else if (isString(theme)) { const resolved = themeResolver.resolve(theme, sourceDir) const { entry, name, shortcut } = resolved @@ -60,7 +60,7 @@ module.exports = async function loadTheme (ctx) { themePath = normalizeThemePath(resolved) themeName = name themeShortcut = shortcut - logger.tip(`\nApply theme ${chalk.gray(themeName)}`) + logger.tip(`Apply theme ${chalk.gray(themeName)}`) } else { throw new Error(`[vuepress] You must specify a theme, or create a local custom theme. \n For more details, refer to https://vuepress.vuejs.org/guide/custom-themes.html#custom-themes. \n`) } diff --git a/packages/@vuepress/core/lib/webpack/DevLogPlugin.js b/packages/@vuepress/core/lib/webpack/DevLogPlugin.js index 254f0bd4dd..4578c18619 100644 --- a/packages/@vuepress/core/lib/webpack/DevLogPlugin.js +++ b/packages/@vuepress/core/lib/webpack/DevLogPlugin.js @@ -25,7 +25,7 @@ module.exports = class DevLogPlugin { const displayUrl = `http://${displayHost}:${port}${publicPath}` logger.success( - `\n${chalk.gray(`[${time}]`)} Build ${chalk.italic(stats.hash.slice(0, 6))} ` + + `${chalk.gray(`[${time}]`)} Build ${chalk.italic(stats.hash.slice(0, 6))} ` + `finished in ${stats.endTime - stats.startTime} ms! ` + ( isFirst diff --git a/packages/@vuepress/core/lib/webpack/createBaseConfig.js b/packages/@vuepress/core/lib/webpack/createBaseConfig.js index ae3861aa5a..9ae6fa39d5 100644 --- a/packages/@vuepress/core/lib/webpack/createBaseConfig.js +++ b/packages/@vuepress/core/lib/webpack/createBaseConfig.js @@ -76,7 +76,7 @@ module.exports = function createBaseConfig ({ .noParse(/^(vue|vue-router|vuex|vuex-router-sync)$/) if (cache === false) { - logger.tip('\nClean cache...\n') + logger.tip('Clean cache...\n') fs.emptyDirSync(cacheDirectory) } diff --git a/packages/@vuepress/plugin-pwa/index.js b/packages/@vuepress/plugin-pwa/index.js index 451fd60175..9001deb690 100644 --- a/packages/@vuepress/plugin-pwa/index.js +++ b/packages/@vuepress/plugin-pwa/index.js @@ -35,7 +35,7 @@ module.exports = (options, context) => ({ const { outDir } = context const swFilePath = path.resolve(outDir, 'service-worker.js') if (serviceWorker) { - logger.wait('\nGenerating service worker...') + logger.wait('Generating service worker...') const wbb = require('workbox-build') await wbb.generateSW({ swDest: swFilePath, diff --git a/packages/@vuepress/shared-utils/lib/logger.js b/packages/@vuepress/shared-utils/lib/logger.js index bc59a1aef6..bbbd1d2aa4 100644 --- a/packages/@vuepress/shared-utils/lib/logger.js +++ b/packages/@vuepress/shared-utils/lib/logger.js @@ -1,56 +1,82 @@ +'use strict' + +/** + * Module dependencies. + */ + const chalk = require('chalk') -const env = require('./env') - -const logger = {} - -const logTypes = { - success: { - color: 'green', - label: 'DONE' - }, - error: { - color: 'red', - label: 'FAIL' - }, - warn: { - color: 'yellow', - label: 'WARN' - }, - tip: { - color: 'cyan', - label: 'TIP' - }, - wait: { - color: 'blue', - label: 'WAIT' + +class Logger { + constructor (options) { + this.options = Object.assign( + { + logLevel: 3 + }, + options + ) } -} -const getLoggerFn = (color, label) => (msg, log = true) => { - let newLine = false - if (msg.startsWith('\n')) { - if (log) msg = msg.slice(1) - newLine = true + setOptions (options) { + Object.assign(this.options, options) + } + + // level: 4 + debug (...args) { + if (this.options.logLevel < 4) { + return + } + + this.status('magenta', 'debug', ...args) } - msg = chalk.reset.inverse.bold[color](` ${label} `) + ' ' + msg - if (log) { - console.log(newLine ? '\n' + msg : msg) - } else { - return msg + + // level: 2 + warn (...args) { + if (this.options.logLevel < 2) { + return + } + console.warn(chalk.yellow('warning'), ...args) } -} -for (const type in logTypes) { - const { color, label } = logTypes[type] - logger[type] = getLoggerFn(color, label) -} + // level: 1 + error (...args) { + if (this.options.logLevel < 1) { + return + } + process.exitCode = process.exitCode || 1 + console.error(chalk.red('error'), ...args) + } + + // level: 3 + success (...args) { + this.status('green', 'success', ...args) + } + + // level: 3 + tip (...args) { + this.status('blue', 'tip', ...args) + } -const debugFn = getLoggerFn('magenta', 'DEBUG') + // level: 3 + info (...args) { + this.status('cyan', 'info', ...args) + } + + wait (...args) { + this.status('cyan', 'wait', ...args) + } -logger.debug = function (msg) { - if (env.isDebug) { - debugFn(msg) + // level: 3 + status (color, label, ...args) { + if (this.options.logLevel < 3) { + return + } + console.log(chalk[color](label), ...args) } } -module.exports = logger +/** + * Expose a logger instance. + */ + +module.exports = new Logger() +