UNPKG

2.4 kBJavaScriptView Raw
1/*
2 Copyright © 2018 Andrew Powell
3
4 This Source Code Form is subject to the terms of the Mozilla Public
5 License, v. 2.0. If a copy of the MPL was not distributed with this
6 file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8 The above copyright notice and this permission notice shall be
9 included in all copies or substantial portions of this Source Code Form.
10*/
11
12const PrefixFactory = require('./factory/PrefixFactory');
13
14const MethodFactory = require('./factory/MethodFactory');
15
16const defaults = {
17 factory: null,
18 level: 'warn',
19 name: +new Date(),
20 prefix: null
21};
22
23module.exports = class LogLevel {
24 constructor(options) {
25 // implement for some _very_ loose type checking. avoids getting into a
26 // circular require between MethodFactory and LogLevel
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 // this.level is a setter, do this after setting up the factory
45 this.level = this.options.level;
46 }
47
48 get factory() {
49 return this.methodFactory;
50 }
51
52 set factory(factory) {
53 // eslint-disable-next-line no-param-reassign
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 // eslint-disable-next-line no-console
83 console.warn('loglevelnext: console is undefined. The log will produce no output.');
84 }
85 }
86
87 get levels() {
88 // eslint-disable-line class-methods-use-this
89 return this.methodFactory.levels;
90 }
91};