logger.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*!
  2. * socket.io-node
  3. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  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. });