index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict';
  2. const chalk = require('chalk');
  3. const loglevel = require('loglevelnext'); //eslint-disable-line
  4. const logSymbols = require('log-symbols');
  5. const uuid = require('uuid/v4');
  6. const symbols = {
  7. trace: chalk.grey('₸'),
  8. debug: chalk.cyan('➤'),
  9. info: logSymbols.info,
  10. warn: logSymbols.warning,
  11. error: logSymbols.error
  12. };
  13. const defaults = {
  14. name: '<unknown>',
  15. level: 'info',
  16. unique: true
  17. };
  18. const prefix = {
  19. level: opts => symbols[opts.level],
  20. template: `{{level}} ${chalk.gray('「{{name}}」')}: `
  21. };
  22. module.exports = function webpackLog(options) {
  23. const opts = Object.assign({}, defaults, options);
  24. const { id } = options;
  25. opts.prefix = Object.assign({}, prefix, options.prefix);
  26. delete opts.id;
  27. Object.defineProperty(opts, 'id', {
  28. get() {
  29. if (!id) {
  30. return this.name + (opts.unique ? `-${uuid()}` : '');
  31. }
  32. return id;
  33. }
  34. });
  35. if (opts.timestamp) {
  36. opts.prefix.template = `[{{time}}] ${opts.prefix.template}`;
  37. }
  38. const log = loglevel.getLogger(opts);
  39. if (!Object.prototype.hasOwnProperty.call(log, 'id')) {
  40. Object.defineProperty(log, 'id', {
  41. get() {
  42. return opts.id;
  43. }
  44. });
  45. }
  46. return log;
  47. };
  48. // NOTE: this is exported so that consumers of webpack-log can use the same
  49. // version of chalk to decorate log messages without incurring additional
  50. // dependency overhead. This is an atypical practice, but chalk version
  51. // segmentation is a common issue.
  52. module.exports.chalk = chalk;
  53. /**
  54. * @NOTE: This is an undocumented function solely for the purpose of tests.
  55. * Do not use this method in production code. Using in production code
  56. * may result in strange behavior.
  57. */
  58. module.exports.delLogger = function delLogger(name) {
  59. delete loglevel.loggers[name];
  60. };
  61. module.exports.factories = loglevel.factories;