LogLevel.js 1.9 KB

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