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