LogLevel.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. 'use strict';
  2. /* global window: true */
  3. /* eslint-disable
  4. multiline-ternary,
  5. no-param-reassign
  6. */
  7. const PrefixFactory = require('./PrefixFactory');
  8. const MethodFactory = require('./MethodFactory');
  9. const defaults = {
  10. name: +new Date(),
  11. level: 'warn',
  12. prefix: null,
  13. factory: null
  14. };
  15. class LogLevel {
  16. constructor(options) {
  17. // implement for some _very_ loose type checking. avoids getting into a
  18. // circular require between MethodFactory and LogLevel
  19. this.type = 'LogLevel';
  20. this.options = Object.assign({}, defaults, options);
  21. this.methodFactory = options.factory;
  22. if (!this.methodFactory) {
  23. const factory = options.prefix
  24. ? new PrefixFactory(this, options.prefix)
  25. : new MethodFactory(this);
  26. this.methodFactory = factory;
  27. }
  28. if (!this.methodFactory.logger) {
  29. this.methodFactory.logger = this;
  30. }
  31. this.name = options.name || '<unknown>';
  32. // this.level is a setter, do this after setting up the factory
  33. this.level = this.options.level;
  34. }
  35. get factory() {
  36. return this.methodFactory;
  37. }
  38. set factory(factory) {
  39. factory.logger = this;
  40. this.methodFactory = factory;
  41. this.methodFactory.replaceMethods(this.level);
  42. }
  43. enable() {
  44. this.level = this.levels.TRACE;
  45. }
  46. disable() {
  47. this.level = this.levels.SILENT;
  48. }
  49. get level() {
  50. return this.currentLevel;
  51. }
  52. set level(logLevel) {
  53. const level = this.methodFactory.distillLevel(logLevel);
  54. if (level == null) {
  55. throw new Error(
  56. `loglevel: setLevel() called with invalid level: ${logLevel}`
  57. );
  58. }
  59. this.currentLevel = level;
  60. this.methodFactory.replaceMethods(level);
  61. if (typeof console === 'undefined' && level < this.levels.SILENT) {
  62. // eslint-disable-next-line no-console
  63. console.warn(
  64. 'loglevel: console is undefined. The log will produce no output'
  65. );
  66. }
  67. }
  68. get levels() { // eslint-disable-line class-methods-use-this
  69. return this.methodFactory.levels;
  70. }
  71. }
  72. module.exports = LogLevel;