Skip to content

Commit

Permalink
feat($core): more concise logger
Browse files Browse the repository at this point in the history
  • Loading branch information
ulivz committed Nov 25, 2018
1 parent 975f568 commit 9c61390
Show file tree
Hide file tree
Showing 10 changed files with 92 additions and 64 deletions.
4 changes: 2 additions & 2 deletions packages/@vuepress/core/lib/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 ---

Expand Down
2 changes: 1 addition & 1 deletion packages/@vuepress/core/lib/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 8 additions & 6 deletions packages/@vuepress/core/lib/plugin-api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.`)
}
})
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions packages/@vuepress/core/lib/prepare/AppContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions packages/@vuepress/core/lib/prepare/CacheLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}
4 changes: 2 additions & 2 deletions packages/@vuepress/core/lib/prepare/loadTheme.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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`)
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@vuepress/core/lib/webpack/DevLogPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/@vuepress/core/lib/webpack/createBaseConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
2 changes: 1 addition & 1 deletion packages/@vuepress/plugin-pwa/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
116 changes: 71 additions & 45 deletions packages/@vuepress/shared-utils/lib/logger.js
Original file line number Diff line number Diff line change
@@ -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()

0 comments on commit 9c61390

Please sign in to comment.