UNPKG

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