forked from Download/ulog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ulog.js
85 lines (72 loc) · 2.37 KB
/
ulog.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
// ulog - microscopically small universal logging library
// © 2017 by Stijn de Witt, some rights reserved
// License: CC-BY-4.0
function log(n){
return !n ? extend(log) : mods[n] || (mods[n] = extend(create(n), log))
}
log.formats = []
log.extends = []
log.enable = function(s) {
var i, split = (s || '').split(/[\s,]+/);
for (i=0; i<split.length; i++) {
if (split[i]) {
s = split[i].replace(/\*/g, '.*?')
if (s[0] === '-') skipMods.push(new RegExp('^' + s.substr(1) + '$'))
else dbgMods.push(new RegExp('^' + s + '$'))
}
}
for (i in mods) patch(mods[i])
}
log.enabled = function(s) {
var i;
for (i=0; i<skipMods.length; i++)
if (skipMods[i].test(s)) return
for (i=0; i<dbgMods.length; i++)
if (dbgMods[i].test(s)) {return true}
}
log.invoke = function(name,args) {
var method = args.length > 1 && names[args[0]] ? args.shift() : 'debug'
for (var i=0; i<log.formats.length; i++) {
log.formats[i](mods[name],method,args)
}
mods[name][method].apply(mods[name], args)
}
log.disable = log.enable.bind(log, '')
var LVL = {ERROR:1, WARN:2, INFO:3, LOG:4, DEBUG:5, TRACE:6},
names = {error:1, warn:2, info:3, log:4, verbose:4, debug:5, trace:6, silly:6, dir:0, table:0, time:0, timeEnd:0, assert:0},
mods = {}, dbgMods = [], skipMods = []
function create(n,r) {
r = (new Function('n', 'log', "return {'" + n + "':function(){log.invoke(n,[].slice.call(arguments))}}[n]"))(n, log)
try {Object.defineProperty(r, 'name', {get:function(){return n}})} catch(e) {}
return r
}
function extend(o,p,l) {
if (o.log) return
o.NONE = 0
o.ulog = {version:'2.0.0-beta.7'}
for (var key in LVL) {o[key] = LVL[key]}
Object.defineProperty(o, 'level', {
get: function(){return l !== undefined ? l : p && p.level},
set: function(n) {
if ((n === undefined) && p) l = undefined
else {
var lvl = n && (Number(n)!==Number(n) ? o[n.toUpperCase()] : Number(n))
if (lvl >= 0 && lvl <= 6) l = lvl
}
patch(o)
if (!p) {for (var mod in mods) {patch(mods[mod])}}
}
})
patch(o)
for (var i=0; i<log.extends.length; i++) log.extends[i](o,p)
return o
}
function patch(o) {
var lvl = Math.max(o.name && log.enabled(o.name) && o.DEBUG || o.level, o.level)
for (var n in names) {
o[n] = lvl < names[n] ? nop : bnd(n) || (typeof print == 'function' && print) || nop
}
}
function bnd(n,c){return (c = log.con()) && (c[n]||c.log).bind(c)}
function nop(){}
module.exports = log