debug.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. /**
  2. * Module dependencies.
  3. */
  4. var tty = require('tty');
  5. /**
  6. * Expose `debug()` as the module.
  7. */
  8. module.exports = debug;
  9. /**
  10. * Enabled debuggers.
  11. */
  12. var names = []
  13. , skips = [];
  14. (process.env.DEBUG || '')
  15. .split(/[\s,]+/)
  16. .forEach(function(name){
  17. name = name.replace('*', '.*?');
  18. if (name[0] === '-') {
  19. skips.push(new RegExp('^' + name.substr(1) + '$'));
  20. } else {
  21. names.push(new RegExp('^' + name + '$'));
  22. }
  23. });
  24. /**
  25. * Colors.
  26. */
  27. var colors = [6, 2, 3, 4, 5, 1];
  28. /**
  29. * Previous debug() call.
  30. */
  31. var prev = {};
  32. /**
  33. * Previously assigned color.
  34. */
  35. var prevColor = 0;
  36. /**
  37. * Is stdout a TTY? Colored output is disabled when `true`.
  38. */
  39. var isatty = tty.isatty(2);
  40. /**
  41. * Select a color.
  42. *
  43. * @return {Number}
  44. * @api private
  45. */
  46. function color() {
  47. return colors[prevColor++ % colors.length];
  48. }
  49. /**
  50. * Humanize the given `ms`.
  51. *
  52. * @param {Number} m
  53. * @return {String}
  54. * @api private
  55. */
  56. function humanize(ms) {
  57. var sec = 1000
  58. , min = 60 * 1000
  59. , hour = 60 * min;
  60. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  61. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  62. if (ms >= sec) return (ms / sec | 0) + 's';
  63. return ms + 'ms';
  64. }
  65. /**
  66. * Create a debugger with the given `name`.
  67. *
  68. * @param {String} name
  69. * @return {Type}
  70. * @api public
  71. */
  72. function debug(name) {
  73. function disabled(){}
  74. disabled.enabled = false;
  75. var match = skips.some(function(re){
  76. return re.test(name);
  77. });
  78. if (match) return disabled;
  79. match = names.some(function(re){
  80. return re.test(name);
  81. });
  82. if (!match) return disabled;
  83. var c = color();
  84. function colored(fmt) {
  85. var curr = new Date;
  86. var ms = curr - (prev[name] || curr);
  87. prev[name] = curr;
  88. fmt = ' \033[9' + c + 'm' + name + ' '
  89. + '\033[3' + c + 'm\033[90m'
  90. + fmt + '\033[3' + c + 'm'
  91. + ' +' + humanize(ms) + '\033[0m';
  92. console.error.apply(this, arguments);
  93. }
  94. function plain(fmt) {
  95. fmt = new Date().toUTCString()
  96. + ' ' + name + ' ' + fmt;
  97. console.error.apply(this, arguments);
  98. }
  99. colored.enabled = plain.enabled = true;
  100. return isatty
  101. ? colored
  102. : plain;
  103. }