log.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. 'use strict';
  2. const { Console } = require('console');
  3. const chalk = require('chalk');
  4. const TRACE = 10;
  5. const DEBUG = 20;
  6. const INFO = 30;
  7. const WARN = 40;
  8. const ERROR = 50;
  9. const FATAL = 60;
  10. const LEVEL_NAMES = {
  11. 10: 'TRACE',
  12. 20: 'DEBUG',
  13. 30: 'INFO ',
  14. 40: 'WARN ',
  15. 50: 'ERROR',
  16. 60: 'FATAL'
  17. };
  18. const LEVEL_COLORS = {
  19. 10: 'gray',
  20. 20: 'gray',
  21. 30: 'green',
  22. 40: 'bgYellow',
  23. 50: 'bgRed',
  24. 60: 'bgRed'
  25. };
  26. const console = new Console({
  27. stdout: process.stdout,
  28. stderr: process.stderr,
  29. colorMode: false
  30. });
  31. class Logger {
  32. constructor(options = {}) {
  33. const silent = options.silent || false;
  34. this._debug = options.debug || false;
  35. this.level = INFO;
  36. if (silent) {
  37. this.level = FATAL + 10;
  38. }
  39. if (this._debug) {
  40. this.level = TRACE;
  41. }
  42. }
  43. _writeLogOutput(level, consoleArgs) {
  44. if (this._debug) {
  45. const str = new Date().toISOString().substring(11, 23) + ' ';
  46. if (level === TRACE || level >= WARN) {
  47. process.stderr.write(chalk[LEVEL_COLORS[DEBUG]](str));
  48. } else {
  49. process.stdout.write(chalk[LEVEL_COLORS[DEBUG]](str));
  50. }
  51. }
  52. if (level >= this.level) {
  53. const str = chalk[LEVEL_COLORS[level]](LEVEL_NAMES[level]) + ' ';
  54. if (level === TRACE || level >= WARN) {
  55. process.stderr.write(str);
  56. } else {
  57. process.stdout.write(str);
  58. }
  59. if (level === TRACE) {
  60. console.trace(...consoleArgs);
  61. } else if (level < INFO) {
  62. console.debug(...consoleArgs);
  63. } else if (level < WARN) {
  64. console.info(...consoleArgs);
  65. } else if (level < ERROR) {
  66. console.warn(...consoleArgs);
  67. } else {
  68. console.error(...consoleArgs);
  69. }
  70. }
  71. }
  72. trace(...args) {
  73. this._writeLogOutput(TRACE, args);
  74. }
  75. debug(...args) {
  76. this._writeLogOutput(DEBUG, args);
  77. }
  78. info(...args) {
  79. this._writeLogOutput(INFO, args);
  80. }
  81. warn(...args) {
  82. this._writeLogOutput(WARN, args);
  83. }
  84. error(...args) {
  85. this._writeLogOutput(ERROR, args);
  86. }
  87. fatal(...args) {
  88. this._writeLogOutput(FATAL, args);
  89. }
  90. }
  91. function createLogger(options) {
  92. const logger = new Logger(options);
  93. logger.d = logger.debug;
  94. logger.i = logger.info;
  95. logger.w = logger.warn;
  96. logger.e = logger.error;
  97. logger.log = logger.info;
  98. return logger;
  99. }
  100. module.exports = createLogger;