-
Notifications
You must be signed in to change notification settings - Fork 1
/
perfLogger.js
633 lines (496 loc) · 15.4 KB
/
perfLogger.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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
"use strict";
const Ttytable = require('tty-table');
const chai = require('chai');
const moment = require('moment');
const _ = require('lodash');
const os = require('os');
const self = {
_tests: {}, // to save tests
_testsSummary: [], // to save totals nb and duration
_isEnabled: false,
_printStartAndEnd: false,
_levels: [],
_LEVEL_TAG_ALL: "***ALL***",
_fSummaryHookFunction: null, // callback to pass the summary object in summary()
_bDisplaySummaryWhenHook: false, // by default, we don't display summary in console if a hook function is defined
_iDefaultCriticityTime: 10, // default criticity level time : 10ms
enable: function(b) {
if (_.isUndefined(b)) {
b = false;
}
chai.expect(b).to.exist.and.be.a('boolean');
self._isEnabled = b;
},
setConfig: function(config) {
chai.expect(config).to.exist.and.be.a('object').and.not.be.empty;
if (!_.isUndefined(config._printStartAndEnd) && !_.isNull(config._printStartAndEnd)) {
self.setPrintStartAndEnd(config._printStartAndEnd);
}
if (config._fSummaryHookFunction) {
self.setHookFunction(config._fSummaryHookFunction);
}
if (!_.isUndefined(config._isEnabled) && !_.isNull(config._isEnabled)) {
self.enable(config._isEnabled);
}
if (!_.isUndefined(config._bDisplaySummaryWhenHook) && !_.isNull(config._bDisplaySummaryWhenHook)) {
self.setDisplaySummaryWhenHook(config._bDisplaySummaryWhenHook);
}
if (config._iDefaultLevelMs) {
self.setDefaultCriticityTime(config._iDefaultLevelMs);
}
},
setPrintStartAndEnd: function(b) {
if (_.isUndefined(b)) {
b = false;
}
chai.expect(b).to.exist.and.be.a('boolean');
self._printStartAndEnd = b;
},
setDefaultCriticityTime: function(iMs) {
chai.expect(iMs).to.be.a('number');
self._iDefaultCriticityTime = iMs;
},
setDisplaySummaryWhenHook: function(b) {
chai.expect(b).to.be.a('boolean');
self._bDisplaySummaryWhenHook = b;
},
start: function(sTag, sParentTag) {
chai.expect(sTag).to.exist.and.be.a('string').and.not.be.empty;
if (!self._isEnabled) {
return;
}
if (!_.isUndefined(sParentTag)) {
chai.expect(sParentTag).to.be.a('string').and.not.be.empty;
}
const newTest = {};
//newTest.timeStart = _.now();
newTest.timeStart = process.hrtime();
newTest.sName = sTag;
if (_.isUndefined(self._tests[sTag])) {
self._tests[sTag] = newTest;
}
const indexSum = _.findIndex(self._testsSummary, {
sName: sTag
});
if (-1 === indexSum) {
const indexLevel = _.findIndex(self._levels, {
sName: sTag
});
let iLevel = 0;
if (-1 === indexLevel) {
const indexLevelAll = _.findIndex(self._levels, {
sName: self._LEVEL_TAG_ALL
});
if (-1 === indexLevelAll) {
iLevel = 10; // 10 ms default if no level defined
} else {
iLevel = self._levels[indexLevelAll].iLevel;
}
} else {
iLevel = self._levels[indexLevel].iDuration;
}
const newTestSummary = {
iNb: 1,
sName: sTag,
iDuration: 0,
iMinDuration: null,
iMaxDuration: null,
iLevel: iLevel,
iNbAboveLevel: 0,
ended: false,
parent: sParentTag
};
self._testsSummary.push(newTestSummary);
}
if (self._printStartAndEnd) {
const sText = "Start %s";
console.log(sText, sTag);
}
},
abort: function(sTag) {
if (!self._isEnabled) {
return;
}
if (!_.isUndefined(self._tests[sTag])) {
delete self._tests[sTag];
}
const indexSum = _.findIndex(self._testsSummary, {
sName: sTag
});
if (indexSum !== -1) {
self._testsSummary.splice(indexSum, 1);
}
},
end: function(sTag) {
chai.expect(sTag).to.exist.and.be.a('string').and.not.be.empty;
if (!self._isEnabled) {
return;
}
if (_.isUndefined(self._tests[sTag])) {
console.error("Fail to end perf measurement of [" + sTag + "] : tag never started.");
return false;
}
// process.hrtime() returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array
const hrDiff = process.hrtime(self._tests[sTag].timeStart);
// we convert hrDiff in ms
// the first element of Array is time in secondes
// the second time tuple Array element is a number of nanoseconds and
// it has to be divided by 1,000,000 in order to get time in milliseconds.
const iDiff = Math.round(hrDiff[0] * 1000) + Math.round(hrDiff[1] / 1000000);
delete self._tests[sTag];
const indexSum = _.findIndex(self._testsSummary, {
sName: sTag
});
chai.expect(indexSum).to.be.a('number').and.above(-1);
self._testsSummary[indexSum].iDuration += iDiff;
self._testsSummary[indexSum].iNb++;
// update min and max of duration
if ((iDiff <= self._testsSummary[indexSum].iMinDuration) || _.isNull(self._testsSummary[indexSum].iMinDuration)) {
self._testsSummary[indexSum].iMinDuration = iDiff;
}
if (iDiff >= self._testsSummary[indexSum].iMaxDuration || _.isNull(self._testsSummary[indexSum].iMaxDuration)) {
self._testsSummary[indexSum].iMaxDuration = iDiff;
}
if (iDiff > self._testsSummary[indexSum].iLevel) {
self._testsSummary[indexSum].iNbAboveLevel++;
}
// mark the tag ended, in order to check the unended ones
self._testsSummary[indexSum].ended = true;
let sDuration = "";
if (self._printStartAndEnd) {
const sLogText = "\n%s executed in : %s";
sDuration = self.humanizeSeconds(iDiff);
return console.log(sLogText, sTag, sDuration);
}
},
/**
* Provides a summary of all the perf measurements
* @param {Boolean} bReset [description]
* @param {string} sOrderAttribute [description]
* @param {string} sOrderSens [description]
* @param {string} sTitle [description]
* @param {function} fCallback [description]
*/
summary: function(options) {
if (_.isUndefined(options) || _.isNull(options)) {
options = {
bReset: false,
sOrderAttribute: 'iDuration',
sOrderSens: 'desc',
sTitle: "",
fCallback: null
};
}
chai.expect(options).to.exist.and.be.a('object').and.not.be.empty;
if (_.isEmpty(options.bReset)) {
options.bReset = true;
}
if (_.isEmpty(options.sOrderAttribute)) {
options.sOrderAttribute = 'iDuration';
}
if (_.isEmpty(options.sOrderSens)) {
options.sOrderSens = 'desc';
}
if (_.isNull(options.sTitle) || _.isUndefined(options.sTitle)) {
options.sTitle = "";
}
// object summary to pass the hook function
const objectSummary = {};
objectSummary.sTitle = options.sTitle;
objectSummary.dDateSummary = new Date();
objectSummary.sVersionNode = process.versions.node; // ex : '5.8.0'
objectSummary.sVersionV8 = process.versions.v8; // ex : '4.1.0.14'
objectSummary.aCPU = os.cpus();
objectSummary.sArchitecture = os.arch();
objectSummary.sPlatform = os.platform(); // ex : 'win32'
objectSummary.sOSName = os.type(); // ex : 'Windows_NT'
objectSummary.sRelease = os.release(); // Returns the operating system release.
objectSummary.iTotalMem = os.totalmem();
objectSummary.iNbSecsUptime = os.uptime();
objectSummary.aRows = [];
if (options.sTitle !== "") {
options.sTitle = "of " + options.sTitle + " ";
}
if (_.isUndefined(options.fCallback) || _.isNull(options.fCallback)) {
if (!_.isNull(self._fSummaryHookFunction) && !_.isUndefined(self._fSummaryHookFunction) && _.isFunction(self._fSummaryHookFunction)) {
options.fCallback = self._fSummaryHookFunction;
}
} else {
chai.expect(options.fCallback).to.be.a('function');
}
chai.expect(options.sOrderAttribute).to.exist.and.be.a('string');
chai.expect(options.sOrderSens).to.exist.and.be.a('string');
chai.expect(options.sTitle).to.exist.and.be.a('string');
if (self._isEnabled) {
if (self._testsSummary.length === 0) {
console.log("perf.summary() : no test stored.");
}
let sDuration = "";
let sAvgDuration = "";
// header config for ttytable
const header = [{
value: "Tag",
headerColor: "grey",
color: "white",
align: "left",
paddingLeft: 1,
width: 40
}, {
value: "Nb",
headerColor: "grey",
color: "white",
align: "center",
paddingLeft: 1,
width: 10
}, {
value: "Total time (s)",
headerColor: "grey",
color: "white",
align: "center",
paddingLeft: 1,
width: 12
}, {
value: "% of grand total",
headerColor: "grey",
color: "white",
align: "center",
paddingLeft: 1,
width: 12
}, {
value: "% of parent",
headerColor: "grey",
color: "white",
align: "center",
paddingLeft: 1,
width: 12
}, {
value: "Min (s)",
headerColor: "grey",
color: "white",
align: "center",
paddingLeft: 1,
width: 10
}, {
value: "Max (s)",
headerColor: "grey",
color: "white",
align: "center",
paddingLeft: 1,
width: 10
}, {
value: "Avg (s)",
headerColor: "grey",
color: "white",
align: "center",
paddingLeft: 1,
width: 10
}, {
value: "Crit. level (s)",
headerColor: "grey",
color: "white",
align: "center",
paddingLeft: 1,
width: 10
}, {
value: "Level status",
headerColor: "grey",
color: "red",
align: "center",
paddingLeft: 1,
width: 10
}, {
value: "% above level",
headerColor: "grey",
color: "white",
align: "center",
paddingLeft: 1,
width: 10
}];
let aSortedTests = _.orderBy(self._testsSummary, [options.sOrderAttribute], [options.sOrderSens]);
let sErrors = "";
const totalDuration = aSortedTests.reduce((acc, test) => {
// if the test has a parent, its duraction is included in its parent's one
// so we don't add it to the total
return acc + (test.parent ? 0 : test.iDuration);
}, 0);
for (const test of aSortedTests) {
if (test.ended === false) {
sErrors += "\nTag [" + test.sName + "] never ended : perf measurement skipped for this tag.\n";
continue;
}
sDuration = "";
sAvgDuration = "";
const iDuration = test.iDuration;
sDuration = self.humanizeSeconds(iDuration);
let iAvgDuration = 0;
iAvgDuration = Math.round(test.iDuration / test.iNb);
sAvgDuration = self.humanizeSeconds(iAvgDuration);
const iPercentOfTotal = Math.round((test.iDuration / totalDuration) * 100);
const sPercentOfTotal = iPercentOfTotal + ' %';
const parentTest = _.find(aSortedTests, { sName: test.parent });
let sPercentOfParent = '';
if (parentTest) {
const iPercentOfParent = Math.round((test.iDuration / parentTest.iDuration) * 100);
sPercentOfParent = iPercentOfParent + ' %';
}
let sAboveLevel = "";
if (test.iNbAboveLevel > 0) {
sAboveLevel = Math.round((test.iNbAboveLevel) / test.iNb * 100) + "%";
} else {
sAboveLevel = "";
}
let sCriticity = "";
if (iAvgDuration > test.iLevel) {
sCriticity = "!";
} else {
sCriticity = "";
}
test.row = [test.sName, test.iNb, sDuration, sPercentOfTotal, sPercentOfParent, self.humanizeSeconds(test.iMinDuration), self.humanizeSeconds(test.iMaxDuration), sAvgDuration, self.humanizeSeconds(test.iLevel), sCriticity, sAboveLevel];
} // END loop for ... on aSortedTest[]
// re-sort tests to represent tree hierarchy between tag/parent tag
const finalTree = [];
// we check if there's a parent tag, if it exists
// if not, delete it
for (const test of aSortedTests) {
if (test.parent) {
const i = _.findIndex(aSortedTests, { sName: test.parent });
if (i === -1) {
console.warn("Tag parent is unknown : " + test.parent);
test.parent = null;
}
}
}
aSortedTests = self.processNames(aSortedTests);
// console.log("*********************************************");
// console.log("aSortedTests après processNames", aSortedTests);
// console.log("*********************************************");
// while not all tests haven't been pushed in the tree
const unpushed = function(arr) {
return arr.some((item) => {
return !item.processed;
});
};
while (unpushed(aSortedTests)) {
for (const test of aSortedTests) {
if (test.ended) {
test.processed = true;
}
if (!test.parent) {
finalTree.push(test);
test.processed = true;
} else {
const i = _.findIndex(finalTree, { sName: test.parent });
if (i !== -1) {
finalTree.splice(i + 1, 0, test);
test.processed = true;
}
}
}
}
// console.log("*********************************************");
// console.log("finalTree", finalTree);
// console.log("*********************************************");
let aRows = finalTree.reduce((arr, test) => {
if (test.ended) {
arr.push(test.row);
}
return arr;
}, []);
let bHookDefined = false;
if (_.isFunction(options.fCallback) && !_.isNull(options.fCallback) && !_.isUndefined(options.fCallback)) {
bHookDefined = true;
}
if (!bHookDefined || (bHookDefined && self._bDisplaySummaryWhenHook)) {
console.log(" -------------------------------------------------------------------" + _.repeat("-", options.sTitle.length));
console.log(" Performance summary " + options.sTitle + moment().format('DD-MM-YYYY HH:mm'));
console.log(" -------------------------------------------------------------------" + _.repeat("-", options.sTitle.length));
const table = Ttytable(header, aRows, {
borderStyle: 1,
paddingBottom: 0,
headerAlign: "center",
align: "center",
color: "white"
});
console.log(table.render());
if (sErrors !== "") {
console.log(" -------- Errors --------");
console.log(sErrors);
}
}
if (bHookDefined) {
objectSummary.aRows = _.filter(self._testsSummary, { ended: true });
options.fCallback(objectSummary);
}
if (options.bReset) {
aSortedTests = [];
aRows = [];
self._tests = {};
self._testsSummary = [];
}
return;
}
},
processNames: function(arrTests) {
// while not all tests haven't been processed
const unprocessed = function(arr) {
return arr.some((item) => {
return !item.renamed;
});
};
const arrProcessed = [];
while (unprocessed(arrTests)) {
for (const test of arrTests) {
if (test.renamed) {
continue;
}
if (!test.parent) {
test.renamed = true;
test.rank = 0;
arrProcessed.push(test);
continue;
}
const parentTest = _.find(arrProcessed, { sName: test.parent });
if (parentTest) {
if (!parentTest.renamed) {
continue;
}
test.rank = parentTest.rank + 1;
if (!test.ended) {
test.renamed = true;
arrProcessed.push(test);
continue;
}
// add 2 dots spaces to indent if the tag has a parent (spaces are removed by tty-table)
test.row[0] = '..'.repeat(test.rank) + test.row[0];
test.renamed = true;
arrProcessed.push(test);
}
}
}
return arrTests;
},
humanizeSeconds: function(iDuration) {
let s = "";
//sDuration = moment.duration(iAvgDuration).minutes() + " mn ";
s = moment.duration(iDuration).seconds() + ".";
s += _.padStart(moment.duration(iDuration).milliseconds(), 3, '0');
return s;
},
setHookFunction: function(f) {
chai.expect(f).to.exist.and.be.a('function');
self._fSummaryHookFunction = f;
},
setLevel: function(sTag, iMs) {
chai.expect(sTag, "sTag should be a defined string").to.exist.and.be.a('string');
chai.expect(iMs, "iMs should be a non empty number").to.exist.and.be.a('number').and.not.be.empty;
if (_.isEmpty(sTag)) {
sTag = self._LEVEL_TAG_ALL;
}
const newLevel = {
sName: sTag,
iDuration: iMs
};
self._levels.push(newLevel);
}
};
module.exports = self;