debug.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /**
  2. * Create a debugger with the given `name`.
  3. *
  4. * @param {String} name
  5. * @return {Type}
  6. * @api public
  7. */
  8. function debug(name) {
  9. if (!debug.enabled(name)) return function(){};
  10. return function(fmt){
  11. var curr = new Date;
  12. var ms = curr - (debug[name] || curr);
  13. debug[name] = curr;
  14. fmt = name
  15. + ' '
  16. + fmt
  17. + ' +' + debug.humanize(ms);
  18. // This hackery is required for IE8
  19. // where `console.log` doesn't have 'apply'
  20. window.console
  21. && console.log
  22. && Function.prototype.apply.call(console.log, console, arguments);
  23. }
  24. }
  25. /**
  26. * The currently active debug mode names.
  27. */
  28. debug.names = [];
  29. debug.skips = [];
  30. /**
  31. * Enables a debug mode by name. This can include modes
  32. * separated by a colon and wildcards.
  33. *
  34. * @param {String} name
  35. * @api public
  36. */
  37. debug.enable = function(name) {
  38. localStorage.debug = name;
  39. var split = (name || '').split(/[\s,]+/)
  40. , len = split.length;
  41. for (var i = 0; i < len; i++) {
  42. name = split[i].replace('*', '.*?');
  43. if (name[0] === '-') {
  44. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  45. }
  46. else {
  47. debug.names.push(new RegExp('^' + name + '$'));
  48. }
  49. }
  50. };
  51. /**
  52. * Disable debug output.
  53. *
  54. * @api public
  55. */
  56. debug.disable = function(){
  57. debug.enable('');
  58. };
  59. /**
  60. * Humanize the given `ms`.
  61. *
  62. * @param {Number} m
  63. * @return {String}
  64. * @api private
  65. */
  66. debug.humanize = function(ms) {
  67. var sec = 1000
  68. , min = 60 * 1000
  69. , hour = 60 * min;
  70. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  71. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  72. if (ms >= sec) return (ms / sec | 0) + 's';
  73. return ms + 'ms';
  74. };
  75. /**
  76. * Returns true if the given mode name is enabled, false otherwise.
  77. *
  78. * @param {String} name
  79. * @return {Boolean}
  80. * @api public
  81. */
  82. debug.enabled = function(name) {
  83. for (var i = 0, len = debug.skips.length; i < len; i++) {
  84. if (debug.skips[i].test(name)) {
  85. return false;
  86. }
  87. }
  88. for (var i = 0, len = debug.names.length; i < len; i++) {
  89. if (debug.names[i].test(name)) {
  90. return true;
  91. }
  92. }
  93. return false;
  94. };
  95. // persist
  96. if (window.localStorage) debug.enable(localStorage.debug);