forked from clux/logule
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogule.js
245 lines (210 loc) · 6.26 KB
/
logule.js
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
var c = require('colors')
, fs = require('fs')
, path = require('path')
, semver = require('semver')
, slice = Array.prototype.slice
, noop = function () {}
, version = require('./package').version;
// Levels and their log output delimiter color fn
var levelMaps = {
'zalgo' : function (str) { return c.magenta(c.zalgo(str)); }
, 'error' : c.red
, 'warn' : c.yellow
, 'info' : c.green
, 'line' : c.bold
, 'debug' : c.cyan
, 'trace' : c.grey
};
var levels = Object.keys(levelMaps);
// Maximum level length
var max_lvl = Math.max.apply({}, levels.map(function (l) {
return l.length;
}));
// Pads a str to a str of length len
function pad(str, len) {
if (str.length < len) {
return str + new Array(len - str.length + 1).join(' ');
} else {
return str;
}
}
// environment based filtering
var globallyOff = [];
if (process.env.LOGULE_SUPPRESS) {
globallyOff = process.env.LOGULE_SUPPRESS.split(',');
}
else if (process.env.LOGULE_ALLOW) {
levels.forEach(function (e) {
globallyOff.push(e);
});
process.env.LOGULE_ALLOW.split(',').forEach(function (a) {
delete globallyOff[globallyOff.indexOf(a)];
});
}
// callsite helper
function getStack() {
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function (err, stack) {
return stack;
};
var err = new Error;
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
}
// Constructor helper
function construct(Ctor, args) {
var F = function () {
Ctor.apply(this, args);
};
F.prototype = Ctor.prototype;
return new F();
}
// Logger class
function Logger() {
// TODO: ES6 name objects for these so we can move stuff out of Ctor
var namespaces = (arguments.length > 0) ? slice.call(arguments, 0) : []
, size = 0
, removed = []
, that = this;
// Expose inspectable info
this.data = {
version : version
, namespaces: namespaces
};
this.options = {
colors: true
, timestamp: function() {
return (new Date).toLocaleTimeString();
}
};
// But dont allow it to be modified
Object.freeze(this.data);
// Internal error logger
// returns a new Logger with one extra namespace, but can log despite filters
function internal() {
return construct(Logger, namespaces.concat(['logule'])).pad(size);
}
// Logger base method
function log() {
var lvl = arguments[0]
, args = (arguments.length > 1) ? slice.call(arguments, 1) : []
, delim = that.options.colors ? levelMaps[lvl]('-') : '-'
, level = pad(lvl, max_lvl).toUpperCase();
if (removed.indexOf(lvl) >= 0 || globallyOff.indexOf(lvl) >= 0) {
return that;
}
var end = namespaces.reduce(function (acc, ns) {
return that.options.colors ?
acc.concat([c.blue(c.bold(pad(ns + '', size))), delim])
: acc.concat([pad(ns + '', size), delim]);
}, []);
var timestamp = that.options.timestamp();
console.log.apply(console, [
that.options.colors ? c.grey(timestamp) : timestamp
, delim
, (lvl === 'error' && that.options.colors) ? c.bold(level) : level
, delim
].concat(end, args));
return that;
}
// Public methods
// Sets or gets an option
this.set = function (name, value) {
if (typeof value == 'undefined') {
return that.options[name];
}
return that.options[name] = value;
};
this.enable = function(name) {
return that.set(name, true);
};
this.disable = function(name) {
return that.set(name, false);
};
// Generate one helper method per specified level
levels.forEach(function (name) {
if (name === 'line') {
return;
}
that[name] = function () {
var args = (arguments.length > 0) ? slice.call(arguments, 0) : [];
return log.apply(that, [name].concat(args));
};
});
// Generate line logger
this.line = function () {
var frame = getStack()[1];
namespaces.push(frame.getFileName() + ":" + frame.getLineNumber());
var c = log.apply(that, ['line'].concat(arguments.length > 0 ? slice.call(arguments, 0) : []));
namespaces.pop();
return c;
};
// Set the padding to size s
this.pad = function (s) {
size = s | 0;
return that;
};
// Suppress logs for specified levels
// Method is cumulative across new subs/gets
this.suppress = function () {
var fns = (arguments.length > 0) ? slice.call(arguments, 0) : [];
fns.forEach(function (fn) {
if (levels.indexOf(fn) < 0) {
internal().warn('Invalid Logule::suppress call for non-method: ' + fn);
}
});
removed = removed.concat(fns).filter(function (e, i, ary) {
return ary.indexOf(e, i + 1) < 0;
});
return that;
};
// Allow logs for specific levels
// Method is cumulative across new subs/gets
this.allow = function () {
var fns = (arguments.length > 0) ? slice.call(arguments, 0) : [];
fns.forEach(function (fn) {
var remIdx = removed.indexOf(fn);
if (remIdx >= 0) {
removed.splice(remIdx, 1);
}
})
return that;
};
// Subclass from a pre-configured Logger class to get extra namespace(s)
this.sub = function () {
var subns = (arguments.length > 0) ? slice.call(arguments, 0) : [];
var sub = construct(Logger, namespaces.concat(subns)).pad(size).suppress.apply({}, removed);
sub.options = that.options;
return sub;
};
// Return a single Logger helper method
this.get = function (fn) {
if (levels.indexOf(fn) < 0) {
internal().error('Invalid Logule::get call for non-method: ' + fn);
}
else if (removed.indexOf(fn) < 0) {
var l = that.sub().suppress.apply({}, levels);
if (fn === 'line') {
return function () {
that.line.apply(l, (arguments.length > 0) ? slice.call(arguments, 0) : []);
};
}
return function () {
log.apply(l, [fn].concat((arguments.length > 0) ? slice.call(arguments, 0) : []));
};
}
return noop;
};
}
// Verify that an instance is an up to date Logger instance
Logger.prototype.verify = function (inst) {
if (!inst || !inst.data || !inst.data.version) {
return false;
}
// inst.version only varies by patch number positively
return semver.satisfies(inst.data.version, "~" + this.data.version);
};
// Expose an instance of Logger
module.exports = new Logger();