logger.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const chalk = require('chalk')
  2. const readline = require('readline')
  3. const padStart = require('string.prototype.padstart')
  4. const EventEmitter = require('events')
  5. exports.events = new EventEmitter()
  6. function _log (type, tag, message) {
  7. if (process.env.VUE_CLI_API_MODE && message) {
  8. exports.events.emit('log', {
  9. message,
  10. type,
  11. tag
  12. })
  13. }
  14. }
  15. const format = (label, msg) => {
  16. return msg.split('\n').map((line, i) => {
  17. return i === 0
  18. ? `${label} ${line}`
  19. : padStart(line, chalk.reset(label).length)
  20. }).join('\n')
  21. }
  22. const chalkTag = msg => chalk.bgBlackBright.white.dim(` ${msg} `)
  23. exports.log = (msg = '', tag = null) => {
  24. tag ? console.log(format(chalkTag(tag), msg)) : console.log(msg)
  25. _log('log', tag, msg)
  26. }
  27. exports.info = (msg, tag = null) => {
  28. console.log(format(chalk.bgBlue.black(' INFO ') + (tag ? chalkTag(tag) : ''), msg))
  29. _log('info', tag, msg)
  30. }
  31. exports.done = (msg, tag = null) => {
  32. console.log(format(chalk.bgGreen.black(' DONE ') + (tag ? chalkTag(tag) : ''), msg))
  33. _log('done', tag, msg)
  34. }
  35. exports.warn = (msg, tag = null) => {
  36. console.warn(format(chalk.bgYellow.black(' WARN ') + (tag ? chalkTag(tag) : ''), chalk.yellow(msg)))
  37. _log('warn', tag, msg)
  38. }
  39. exports.error = (msg, tag = null) => {
  40. console.error(format(chalk.bgRed(' ERROR ') + (tag ? chalkTag(tag) : ''), chalk.red(msg)))
  41. _log('error', tag, msg)
  42. if (msg instanceof Error) {
  43. console.error(msg.stack)
  44. _log('error', tag, msg.stack)
  45. }
  46. }
  47. exports.clearConsole = title => {
  48. if (process.stdout.isTTY) {
  49. const blank = '\n'.repeat(process.stdout.rows)
  50. console.log(blank)
  51. readline.cursorTo(process.stdout, 0, 0)
  52. readline.clearScreenDown(process.stdout)
  53. if (title) {
  54. console.log(title)
  55. }
  56. }
  57. }
  58. // silent all logs except errors during tests and keep record
  59. if (process.env.VUE_CLI_TEST) {
  60. require('./_silence')('logs', exports)
  61. }