forked from EyalAr/brolog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrolog.js
599 lines (521 loc) · 17.2 KB
/
brolog.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
(function (root, factory) {
if (typeof define === 'function' && define.amd) define([], factory);
else if (typeof exports === 'object') module.exports = factory();
else root.Logger = factory();
}(this, function(){
var ARRAY_SLICE = Array.prototype.slice,
ARRAY_PUSH = Array.prototype.push,
LOCAL_PRINTERS = {},
DEFAULT_PRINTER = _getConsolePrinter('*', (() => { try { return window.console } catch (e) { return global.console } })() ),
PRINTERS = [ DEFAULT_PRINTER ];
var QUERY_PARAM_DIRECTIVE = 'brolog';
var LEVELS = [
'TRA',
'DBG',
'INF',
'WRN',
'ERR',
'OFF'
].reduce(function(p, e, i, o){
p.toNumber[e] = i;
p.toString[i] = e;
return p;
}, {
toNumber: {},
toString: {}
});
var LOCAL_LOGGERS = {};
function _getLoggerByName(loggerName, newLogger, newLoggerId) {
if (newLoggerId && (!loggerName || loggerName === true)) {
loggerName = 'Logger_' + newLoggerId;
}
if (loggerName === '*' || !loggerName || loggerName === true) {
return null;
} else {
loggerName = ''+clearName(loggerName);
var localLogger = LOCAL_LOGGERS[loggerName] || newLogger || new Logger(loggerName);
localLogger.name = loggerName;
if (!!newLoggerId) {
localLogger.id = newLoggerId;
}
newLoggerId = localLogger.id;
LOCAL_LOGGERS[loggerName] = localLogger;
///LOCAL_LOGGERS[newLoggerId] = localLogger;
return localLogger;
}
};
var gLevel = LEVELS.toNumber.OFF,
gCounter = 0,
lCounter = 0,
gNameFilter,
gStart;
if ((() => { try { return window } catch (e) { return undefined } })() && window.location){
var qs = window.location.search || "",
re = new RegExp("[&\\?]" + QUERY_PARAM_DIRECTIVE + "=([^#&]*)"),
m = qs.match(re),
l;
if (m) l = LEVELS.toNumber[m[1].toUpperCase()];
if (l !== undefined) gLevel = l;
}
var dirname = function(path) {
if (!path || path === true) {
return path;
}
path = _simplifySlashesAndLinebreaks(path);
var first = path[0];
if (first !== '/' && !(first === '.' && (path[1] === '/' || path[1] === '.'))) {
first = '.';
path = first + '/'+ path;
}
while (path.endsWith('/')) {
path = path.substring(0, path.length-1);
}
if (path.length <= 1 || path === '..') {
return path || first;
}
path = path.substring(0, path.lastIndexOf('/'));
if (path.length <= 0) {
path = first;
}
if (!path.endsWith('/')) {
path += '/';
}
return path;
}
var basename = function(path) {
if (!path || path === true) {
return path;
}
path = _simplifySlashesAndLinebreaks(path);
while(path.endsWith('/')) {
path = path.substring(0, path.length-1);
}
return path.substring(path.lastIndexOf('/')+1);
}
var allfamily = function(path) {
if (!path || path === true) {
return [];
}
var results = [path];
var parentPath;
while (true) {
parentPath = dirname(results[0]);
if (parentPath === results[0] || !parentPath) {
break;
}
results.unshift(parentPath);
}
return results;
}
var mkdirp = function(path) {
var familyTree = allfamily(path);
var p;
for (p of familyTree) {
try {
require('fs').mkdirSync(p);
try {
require('fs').chmodSync(p, 0o777);
} catch (e0) {
}
} catch (e) {
}
}
}
function _simplifySlashes(fullFileName) {
fullFileName = fullFileName.replace(/\\/g, '/'); // safety from win paths: 1
return fullFileName;
}
function _simplifySlashesAndLinebreaks(fullFileName) {
fullFileName = _simplifySlashes(fullFileName);
fullFileName = fullFileName.replace(/\r\n/g, '\r'); // safety from win paths: 2.1
fullFileName = fullFileName.replace(/\r/g, '\n'); // safety from mac paths: 2.2
fullFileName = fullFileName.replace(/\t/g, ' '); // safety from tabs: 3
return fullFileName.trim();
}
function clearName(fullFileName) {
if (!fullFileName || fullFileName === true) {
return fullFileName;
} else {
fullFileName = ''+fullFileName;
}
//console.error('fullFileName: ', fullFileName);
fullFileName = _simplifySlashesAndLinebreaks(fullFileName);
fullFileName = fullFileName.replace(/\n/g, '_br_'); // safety from lin paths: 2.3
if (fullFileName.indexOf('/') < 0) {
return fullFileName;
} else {
let tmpArr = fullFileName.split('/');
fullFileName = tmpArr[tmpArr.length-1]; // to short path
tmpArr = fullFileName.split('.');
fullFileName = tmpArr[0]; // to short name
return fullFileName;
}
}
/**
* Constructor
*/
function Logger(name){
this.id = lCounter++;
var localLogger = _getLoggerByName(name, this, this.id) || {"name": name, "id": this.id};
if (!!localLogger && !!localLogger.id) {
this.id = localLogger.id;
}
this.name = (!!localLogger && !!localLogger.name) ? (localLogger.name) : ('Logger ' + this.id);
this.hasGivenName = !!name && name !== '*';
this.level = LEVELS.toNumber.TRA;
this.counter = 0;
this.start = null;
localLogger = this;
if (this.hasGivenName) {
LOCAL_LOGGERS[this.name] = localLogger; ///
}
// whatever is here will be sent as meta data to the log printers,
// *only* for the next log message, and then will be reset back to 'null'.
this.meta = null;
}
/**
* Filterting rules:
* 1. Should be at least as severe as the global level
* 2. Should be at least as severe as the local level
* 3. logger's name should pass name filter
*/
function allow(logger, level){
if (level < gLevel) return false;
if (level < logger.level) return false;
if (gNameFilter && !gNameFilter.test(logger.name)) return false;
return true;
}
function _getConsolePrinter(targetLogger, console){
var clog = console && console.log ? getInterface('log') : function(){},
cdbg = console && console.debug ? getInterface('debug') : clog,
cwrn = console && console.warn ? getInterface('warn') : clog,
cerr = console && console.error ? getInterface('error') : clog;
return function(gCounter, gStart, logger, nLevel, sLevel, msgs, meta){
var _msgs = [
"[" + gCounter + " " + (Date.now() - gStart) + "]",
"[" + logger.name + "]",
"[" + logger.counter + " " + (Date.now() - logger.start) + "]",
"[" + sLevel + "]"
];
ARRAY_PUSH.apply(_msgs, msgs);
switch(sLevel){
case "TRA":
case "DBG":
cdbg.apply(null, _msgs);
break;
case "ERR":
cerr.apply(null, _msgs);
break;
case "WRN":
cwrn.apply(null, _msgs);
break;
case "INF":
clog.apply(null, _msgs);
break;
default:
clog.apply(null, _msgs);
break;
}
};
function getInterface(method){
if (Function.prototype.bind && typeof console[method] === "object") {
//IE9
return Function.prototype.call.bind(console[method], console);
} else {
//others
return console[method].bind(console);
}
}
}
function _getFilePrinter(targetLogger, outFileName, customDelimiter){
var flog = getInterface('fs') || function(){};
if (!customDelimiter || customDelimiter === true) {
customDelimiter = ', ';
}
if (!outFileName) {
throw 'outFileName is not correct: '+outFileName;
}
if (!targetLogger) {
targetLogger = _getLoggerByName(outFileName);
}
mkdirp(dirname(outFileName));
return function(gCounter, gStart, logger, nLevel, sLevel, msgs, meta){
var _msgs = [
"[" + gCounter + " " + (Date.now() - gStart) + "]",
"[" + logger.name + "]",
"[" + logger.counter + " " + (Date.now() - logger.start) + "]",
"[" + sLevel + "]"
];
ARRAY_PUSH.apply(_msgs, msgs);
_msgs = _msgs.map(function(el) {
return cleanStringify(el);
});
var bigMessage = _msgs.join(customDelimiter);
flog.writeFileSync(outFileName, bigMessage + '<br/>\n', {
"encoding": 'utf8',
"flag": 'a',
"mode": 0o666, // but not forget about folder: 0o777
});
try {
flog.chmodSync(outFileName, 0o666);
} catch (e0) {
}
};
function getInterface(method){
if (typeof global !== "undefined" || typeof window === "undefined") {
//NodeJS
return require('fs');
} else {
//browsers
return {
writeFileSync: function(outFileName, message, encoding) {
return console.log(outFileName, message, encoding);
},
chmodSync: function(outFileName, mode) {
return undefined;
},
};
}
}
}
function addFileLogger(targetScriptName, customDelimiter) {
targetScriptName = _simplifySlashesAndLinebreaks(targetScriptName, customDelimiter);
var parentDir = dirname(targetScriptName);
var parentShort = basename(parentDir);
var grandpaDir = dirname(parentDir);
var logsDir = grandpaDir + 'logs/' + parentShort + '/';
var targetLogger = _getLoggerByName(targetScriptName);
var outFileName = logsDir+targetLogger.name+'.log.htm';
var filePrinter = _getFilePrinter(targetLogger, outFileName, customDelimiter);
targetLogger.addLocalPrinter(filePrinter);
}
function addConsoleLogger(targetScriptName, customDelimiter) {
targetScriptName = _simplifySlashesAndLinebreaks(targetScriptName, customDelimiter);
var targetLogger = _getLoggerByName(targetScriptName);
var consolePrinter = _getConsolePrinter(targetLogger, customDelimiter);
targetLogger.addLocalPrinter(consolePrinter);
}
function _print(logger, level, args){
if (!allow(logger, level)) return;
if (!gStart) gStart = Date.now();
if (!logger.start) logger.start = Date.now();
gCounter++;
logger.counter++;
args = ARRAY_SLICE.apply(args);
PRINTERS.forEach(function(printer){
printer(gCounter, gStart, logger, level, LEVELS.toString[level], args, logger.meta);
});
if (!!logger.name && logger.name !== '*' && !!LOCAL_PRINTERS[logger.name]) {
LOCAL_PRINTERS[logger.name].forEach(function(printer){
printer(gCounter, gStart, logger, level, LEVELS.toString[level], args, logger.meta);
});
}
logger.meta = null;
return args.join(" ");
}
Logger.getConsolePrinter = _getConsolePrinter.bind(this, '*');
Logger.addFileLogger = addFileLogger;
Logger.addConsoleLogger = addConsoleLogger;
function callerName() {
try {
var myCallee = arguments.callee;
var hisCallee = myCallee.caller.arguments.callee;
var hisCallerName = hisCallee.caller.name;
if (isNoE(hisCallerName)) {
var hisCallersFunction = hisCallee.caller.toString();
if (!isNoE(hisCallersFunction)) {
hisCallerName = fBetween(hisCallersFunction, "function", "(");
}
}
hisCallerName = hisCallerName.trim();
} catch (ex) {
hisCallerName = "";
}
if (isNoE(hisCallerName)) {
var e0 = new Error('e0');
var s0 = e0.stack.split('\n');
return '('+((s0[3] || s0[2] || s0[1] || 'at anonymous').trim())+')';
}
return hisCallerName;
}
///////////////////////////////////////
function getStringValue(inString) {
if (inString == null || inString == "undefined" || inString == "null" || inString == "[object]" || inString == "[object NodeList]") {
return "";
}
try {
var tString = new String(inString);
return tString.toString();
} catch (e) {
return "";
}
}
function fLeft(inText, delim) {
inText = getStringValue(inText);
delim = getStringValue(delim);
var outText = "";
var theSpot = inText.indexOf(delim);
if (theSpot > -1) {
outText = inText.substring(0, theSpot);
}
return outText;
}
function fLeftBack(inText, delim) {
inText = getStringValue(inText);
delim = getStringValue(delim);
var outText = "";
var theSpot = inText.lastIndexOf(delim);
if (theSpot > -1) outText = inText.substring(0, theSpot);
return outText;
}
function fRight(inText, delim) {
inText = getStringValue(inText);
delim = getStringValue(delim);
var outText = "";
var theSpot = inText.indexOf(delim);
if (theSpot > -1) {
outText = inText.substring(theSpot + delim.length, inText.length);
}
return outText;
}
function fRightBack(inText, delim) {
inText = getStringValue(inText);
delim = getStringValue(delim);
var outText = "";
var theSpot = inText.lastIndexOf(delim);
if (theSpot > -1) outText = inText.substring(theSpot + delim.length, inText.length);
return outText;
}
function fBetween(inText, delimLeft, delimRight) {
return fLeft(fRight(inText, delimLeft), delimRight);
}
function isNoE(obj) {
return isNullOrEmpty(obj);
}
function isNullOrEmpty(obj) {
// must test type of base object first
if (typeof obj == "undefined") {
return true;
}
// immediate
if (obj == undefined || obj == null) {
return true;
}
// STRING
return getStringValue(obj) == "";
}
///////////////////////////////////////
function cleanStringify(object) {
if (object && typeof object === 'object') {
let wasArray = Array.isArray(object);
object = copyWithoutCircularReferences([object], object);
if (wasArray && !Array.isArray(object)) {
object = Object.values(object);
}
}
return JSON.stringify(object);
function copyWithoutCircularReferences(references, object) {
var cleanObject = {};
Object.keys(object).forEach(function(key) {
var value = object[key];
let wasArray = Array.isArray(value);
if (value && typeof value === 'object' && !(value instanceof String)) {
if (references.indexOf(value) < 0) {
references.push(value);
cleanObject[key] = copyWithoutCircularReferences(references, value);
if (wasArray && !Array.isArray(cleanObject[key])) {
cleanObject[key] = Object.values(cleanObject[key]);
}
references.pop();
} else {
cleanObject[key] = '###_Circular_###';
}
} else {
if (typeof value === 'function' || !(value === true || value === false || value === null || value === undefined || typeof value === 'number')) {
value = ''+value;
}
cleanObject[key] = value;
}
});
return cleanObject;
}
}
Logger.prototype.trace = Logger.prototype.tra = function(){
return _print(this, LEVELS.toNumber.TRA, Object.values(arguments).concat([callerName()]));
};
Logger.prototype.log = Logger.prototype.info = Logger.prototype.inf = function(){
return _print(this, LEVELS.toNumber.INF, Object.values(arguments).concat([callerName()]));
};
Logger.prototype.debug = Logger.prototype.dbg = function(){
return _print(this, LEVELS.toNumber.DBG, Object.values(arguments).concat([callerName()]));
};
Logger.prototype.warn = Logger.prototype.wrn = function(){
return _print(this, LEVELS.toNumber.WRN, Object.values(arguments).concat([callerName()]));
};
Logger.prototype.error = Logger.prototype.err = function(){
return _print(this, LEVELS.toNumber.ERR, Object.values(arguments).concat([callerName()]));
};
Logger.prototype.setOff = Logger.prototype.off = function(){
this.level = LEVELS.toNumber.OFF;
};
Logger.prototype.with = function(meta){
this.meta = meta;
return this;
};
Logger.prototype.setTrace = function(){
this.level = LEVELS.toNumber.TRA;
};
Logger.prototype.setDebug = function(){
this.level = LEVELS.toNumber.DBG;
};
Logger.prototype.setInfo = Logger.prototype.setInf = Logger.prototype.setLog = function(){
this.level = LEVELS.toNumber.INF;
};
Logger.prototype.setWarn = function(){
this.level = LEVELS.toNumber.WRN;
};
Logger.prototype.setError = Logger.prototype.setErr = function(){
this.level = LEVELS.toNumber.ERR;
};
Logger.setOff = Logger.off = function(){
gLevel = LEVELS.toNumber.OFF;
};
Logger.setTrace = function(){
gLevel = LEVELS.toNumber.TRA;
};
Logger.setDebug = function(){
gLevel = LEVELS.toNumber.DBG;
};
Logger.setInfo = Logger.setInf = Logger.setLog = function(){
gLevel = LEVELS.toNumber.INF;
};
Logger.setWarn = function(){
gLevel = LEVELS.toNumber.WRN;
};
Logger.setError = Logger.setErr = function(){
gLevel = LEVELS.toNumber.ERR;
};
Logger.filterName = function(filter){
if (!(filter instanceof RegExp))
if (typeof filter == 'string' || filter instanceof String)
filter = new RegExp("^" + filter + "$");
else throw Error("'filter' must be a RegExp or a string");
gNameFilter = filter;
};
Logger.addPrinter = function(printer){
if (typeof(printer) !== 'function') throw Error("'printer' must be a function");
PRINTERS.push(printer);
};
Logger.prototype.addLocalPrinter = function(printer){
if (typeof(printer) !== 'function') throw Error("'printer' must be a function");
if (!!this && this !== true) {
LOCAL_PRINTERS[this.name || '*'] = LOCAL_PRINTERS[this.name || '*'] || [];
LOCAL_PRINTERS[this.name || '*'].push(printer);
} else {
LOCAL_PRINTERS['*'] = LOCAL_PRINTERS['*'] || [];
LOCAL_PRINTERS['*'].push(printer);
}
};
LOCAL_PRINTERS['*'] = PRINTERS;
return Logger;
}));