log.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.makeLog = void 0;
  4. var util = require('util');
  5. var colors = {
  6. info: '36',
  7. error: '31;1',
  8. warn: '33',
  9. debug: '90',
  10. };
  11. var formatDate = function (date) {
  12. return [date.getHours(), date.getMinutes(), date.getSeconds()]
  13. .map(function (n) { return n.toString().padStart(2, '0'); })
  14. .join(':');
  15. };
  16. /**
  17. * Logs a message to the console. The level is displayed in ANSI colors,
  18. * either bright red in case of an error or green otherwise.
  19. */
  20. exports.makeLog = function (cfg) {
  21. function log(msg, level) {
  22. if (cfg.quiet && level === 'info')
  23. return;
  24. if (cfg.timestamp)
  25. msg = color(formatDate(new Date()), '30;1') + ' ' + msg;
  26. var c = colors[level.toLowerCase()] || '32';
  27. console.log('[' + color(level.toUpperCase(), c) + '] ' + msg);
  28. }
  29. function color(s, c) {
  30. if (process.stdout.isTTY) {
  31. return '\x1B[' + c + 'm' + s + '\x1B[0m';
  32. }
  33. return s;
  34. }
  35. log.debug = function () {
  36. if (!cfg.debug)
  37. return;
  38. log(util.format.apply(util, arguments), 'debug');
  39. };
  40. log.info = function () {
  41. log(util.format.apply(util, arguments), 'info');
  42. };
  43. log.warn = function () {
  44. log(util.format.apply(util, arguments), 'warn');
  45. };
  46. log.error = function () {
  47. log(util.format.apply(util, arguments), 'error');
  48. };
  49. return log;
  50. };