to-console.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. var fancyLog = require('fancy-log');
  3. /* istanbul ignore next */
  4. function noop() {}
  5. // The sorting of the levels is
  6. // significant.
  7. var levels = [
  8. 'error', // -L: Logs error events.
  9. 'warn', // -LL: Logs warn and error events.
  10. 'info', // -LLL: Logs info, warn and error events.
  11. 'debug', // -LLLL: Logs all log levels.
  12. ];
  13. function cleanup(log) {
  14. levels.forEach(removeListeners);
  15. function removeListeners(level) {
  16. if (level === 'error') {
  17. log.removeListener(level, noop);
  18. log.removeListener(level, fancyLog.error);
  19. } else {
  20. log.removeListener(level, fancyLog);
  21. }
  22. }
  23. }
  24. function toConsole(log, opts) {
  25. // Remove previous listeners to enable to call this twice.
  26. cleanup(log);
  27. // Return immediately if logging is
  28. // not desired.
  29. if (opts.tasksSimple || opts.tasksJson || opts.help || opts.version || opts.silent) {
  30. // Keep from crashing process when silent.
  31. log.on('error', noop);
  32. return;
  33. }
  34. // Default loglevel to info level (3).
  35. var loglevel = opts.logLevel || 3;
  36. levels
  37. .filter(function(item, i) {
  38. return i < loglevel;
  39. })
  40. .forEach(function(level) {
  41. if (level === 'error') {
  42. log.on(level, fancyLog.error);
  43. } else {
  44. log.on(level, fancyLog);
  45. }
  46. });
  47. }
  48. module.exports = toConsole;