1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const PrefixFactory = require('./factory/PrefixFactory');
|
13 |
|
14 | const MethodFactory = require('./factory/MethodFactory');
|
15 |
|
16 | const defaults = {
|
17 | factory: null,
|
18 | level: 'warn',
|
19 | name: +new Date(),
|
20 | prefix: null
|
21 | };
|
22 |
|
23 | module.exports = class LogLevel {
|
24 | constructor(options) {
|
25 |
|
26 |
|
27 | this.type = 'LogLevel';
|
28 | this.options = Object.assign({}, defaults, options);
|
29 | this.methodFactory = options.factory;
|
30 |
|
31 | if (!this.methodFactory) {
|
32 | const factory = options.prefix
|
33 | ? new PrefixFactory(this, options.prefix)
|
34 | : new MethodFactory(this);
|
35 | this.methodFactory = factory;
|
36 | }
|
37 |
|
38 | if (!this.methodFactory.logger) {
|
39 | this.methodFactory.logger = this;
|
40 | }
|
41 |
|
42 | this.name = options.name || '<unknown>';
|
43 |
|
44 |
|
45 | this.level = this.options.level;
|
46 | }
|
47 |
|
48 | get factory() {
|
49 | return this.methodFactory;
|
50 | }
|
51 |
|
52 | set factory(factory) {
|
53 |
|
54 | factory.logger = this;
|
55 | this.methodFactory = factory;
|
56 | this.methodFactory.replaceMethods(this.level);
|
57 | }
|
58 |
|
59 | disable() {
|
60 | this.level = this.levels.SILENT;
|
61 | }
|
62 |
|
63 | enable() {
|
64 | this.level = this.levels.TRACE;
|
65 | }
|
66 |
|
67 | get level() {
|
68 | return this.currentLevel;
|
69 | }
|
70 |
|
71 | set level(logLevel) {
|
72 | const level = this.methodFactory.distillLevel(logLevel);
|
73 |
|
74 | if (level === false || level == null) {
|
75 | throw new RangeError(`loglevelnext: setLevel() called with invalid level: ${logLevel}`);
|
76 | }
|
77 |
|
78 | this.currentLevel = level;
|
79 | this.methodFactory.replaceMethods(level);
|
80 |
|
81 | if (typeof console === 'undefined' && level < this.levels.SILENT) {
|
82 |
|
83 | console.warn('loglevelnext: console is undefined. The log will produce no output.');
|
84 | }
|
85 | }
|
86 |
|
87 | get levels() {
|
88 |
|
89 | return this.methodFactory.levels;
|
90 | }
|
91 | };
|