log.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. var colour = require('./colour');
  2. var bus = require('./bus');
  3. var required = false;
  4. var useColours = true;
  5. var coding = {
  6. log: 'black',
  7. info: 'yellow',
  8. status: 'green',
  9. detail: 'yellow',
  10. fail: 'red',
  11. error: 'red',
  12. };
  13. function log(type, text) {
  14. var msg = '[nodemon] ' + (text || '');
  15. if (useColours) {
  16. msg = colour(coding[type], msg);
  17. }
  18. // always push the message through our bus, using nextTick
  19. // to help testing and get _out of_ promises.
  20. process.nextTick(() => {
  21. bus.emit('log', { type: type, message: text, colour: msg });
  22. });
  23. // but if we're running on the command line, also echo out
  24. // question: should we actually just consume our own events?
  25. if (!required) {
  26. if (type === 'error') {
  27. console.error(msg);
  28. } else {
  29. console.log(msg || '');
  30. }
  31. }
  32. }
  33. var Logger = function (r) {
  34. if (!(this instanceof Logger)) {
  35. return new Logger(r);
  36. }
  37. this.required(r);
  38. return this;
  39. };
  40. Object.keys(coding).forEach(function (type) {
  41. Logger.prototype[type] = log.bind(null, type);
  42. });
  43. // detail is for messages that are turned on during debug
  44. Logger.prototype.detail = function (msg) {
  45. if (this.debug) {
  46. log('detail', msg);
  47. }
  48. };
  49. Logger.prototype.required = function (val) {
  50. required = val;
  51. };
  52. Logger.prototype.debug = false;
  53. Logger.prototype._log = function (type, msg) {
  54. if (required) {
  55. bus.emit('log', { type: type, message: msg || '', colour: msg || '' });
  56. } else if (type === 'error') {
  57. console.error(msg);
  58. } else {
  59. console.log(msg || '');
  60. }
  61. };
  62. Object.defineProperty(Logger.prototype, 'useColours', {
  63. set: function (val) {
  64. useColours = val;
  65. },
  66. get: function () {
  67. return useColours;
  68. },
  69. });
  70. module.exports = Logger;