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