logger.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*!
  2. * socket.io-node
  3. * Copyright(c) 2011 LearnBoost <[email protected]>
  4. * MIT Licensed
  5. */
  6. /**
  7. * Module dependencies.
  8. */
  9. var util = require('./util')
  10. , toArray = util.toArray;
  11. /**
  12. * Log levels.
  13. */
  14. var levels = [
  15. 'error'
  16. , 'warn'
  17. , 'info'
  18. , 'debug'
  19. ];
  20. /**
  21. * Colors for log levels.
  22. */
  23. var colors = [
  24. 31
  25. , 33
  26. , 36
  27. , 90
  28. ];
  29. /**
  30. * Pads the nice output to the longest log level.
  31. */
  32. function pad (str) {
  33. var max = 0;
  34. for (var i = 0, l = levels.length; i < l; i++)
  35. max = Math.max(max, levels[i].length);
  36. if (str.length < max)
  37. return str + new Array(max - str.length + 1).join(' ');
  38. return str;
  39. };
  40. /**
  41. * Logger (console).
  42. *
  43. * @api public
  44. */
  45. var Logger = module.exports = function (opts) {
  46. opts = opts || {}
  47. this.colors = false !== opts.colors;
  48. this.level = 3;
  49. this.enabled = true;
  50. };
  51. /**
  52. * Log method.
  53. *
  54. * @api public
  55. */
  56. Logger.prototype.log = function (type) {
  57. var index = levels.indexOf(type);
  58. if (index > this.level || !this.enabled)
  59. return this;
  60. console.log.apply(
  61. console
  62. , [this.colors
  63. ? ' \033[' + colors[index] + 'm' + pad(type) + ' -\033[39m'
  64. : type + ':'
  65. ].concat(toArray(arguments).slice(1))
  66. );
  67. return this;
  68. };
  69. /**
  70. * Generate methods.
  71. */
  72. levels.forEach(function (name) {
  73. Logger.prototype[name] = function () {
  74. this.log.apply(this, [name].concat(toArray(arguments)));
  75. };
  76. });