performance-monitor-logger
Version:
Performance monitor logger for Angular applications
1,466 lines • 72.8 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common/http'), require('rxjs/operators')) :
typeof define === 'function' && define.amd ? define('performance-monitor-logger', ['exports', '@angular/core', '@angular/common/http', 'rxjs/operators'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['performance-monitor-logger'] = {}, global.ng.core, global.ng.common.http, global.rxjs.operators));
}(this, (function (exports, i0, http, operators) { 'use strict';
var PerformanceMonitorComponent = /** @class */ (function () {
function PerformanceMonitorComponent() {
}
PerformanceMonitorComponent.prototype.ngOnInit = function () { };
return PerformanceMonitorComponent;
}());
PerformanceMonitorComponent.decorators = [
{ type: i0.Component, args: [{
selector: 'lib-performanceMonitorLogger',
template: " <p>performance-monitor-logger works!</p> "
},] }
];
PerformanceMonitorComponent.ctorParameters = function () { return []; };
// performance-monitor.module.ts
var PerformanceMonitorModule = /** @class */ (function () {
function PerformanceMonitorModule() {
}
return PerformanceMonitorModule;
}());
PerformanceMonitorModule.decorators = [
{ type: i0.NgModule, args: [{
declarations: [PerformanceMonitorComponent],
imports: [],
exports: [PerformanceMonitorComponent],
},] }
];
var PerformanceMonitorService = /** @class */ (function () {
function PerformanceMonitorService() {
}
return PerformanceMonitorService;
}());
PerformanceMonitorService.ɵprov = i0.ɵɵdefineInjectable({ factory: function PerformanceMonitorService_Factory() { return new PerformanceMonitorService(); }, token: PerformanceMonitorService, providedIn: "root" });
PerformanceMonitorService.decorators = [
{ type: i0.Injectable, args: [{
providedIn: 'root'
},] }
];
PerformanceMonitorService.ctorParameters = function () { return []; };
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b)
if (Object.prototype.hasOwnProperty.call(b, p))
d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); };
}
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function")
throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn)
context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access)
context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done)
throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0)
continue;
if (result === null || typeof result !== "object")
throw new TypeError("Object expected");
if (_ = accept(result.get))
descriptor.get = _;
if (_ = accept(result.set))
descriptor.set = _;
if (_ = accept(result.init))
initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field")
initializers.unshift(_);
else
descriptor[key] = _;
}
}
if (target)
Object.defineProperty(target, contextIn.name, descriptor);
done = true;
}
;
function __runInitializers(thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
}
;
function __propKey(x) {
return typeof x === "symbol" ? x : "".concat(x);
}
;
function __setFunctionName(f, name, prefix) {
if (typeof name === "symbol")
name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
}
;
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try {
step(generator.next(value));
}
catch (e) {
reject(e);
} }
function rejected(value) { try {
step(generator["throw"](value));
}
catch (e) {
reject(e);
} }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function () { if (t[0] & 1)
throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _)
try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
}
catch (e) {
op = [6, e];
y = 0;
}
finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function (o, m, k, k2) {
if (k2 === undefined)
k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function () { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function (o, m, k, k2) {
if (k2 === undefined)
k2 = k;
o[k2] = m[k];
});
function __exportStar(m, o) {
for (var p in m)
if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
__createBinding(o, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m)
return m.call(o);
if (o && typeof o.length === "number")
return {
next: function () {
if (o && i >= o.length)
o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
}
catch (error) {
e = { error: error };
}
finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
}
finally {
if (e)
throw e.error;
}
}
return ar;
}
/** @deprecated */
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/** @deprecated */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++)
s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2)
for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar)
ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
function verb(n, f) { if (g[n]) {
i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); };
if (f)
i[n] = f(i[n]);
} }
function resume(n, v) { try {
step(g[n](v));
}
catch (e) {
settle(q[0][3], e);
} }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length)
resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) {
Object.defineProperty(cooked, "raw", { value: raw });
}
else {
cooked.raw = raw;
}
return cooked;
}
;
var __setModuleDefault = Object.create ? (function (o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function (o, v) {
o["default"] = v;
};
var ownKeys = function (o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o)
if (Object.prototype.hasOwnProperty.call(o, k))
ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
function __importStar(mod) {
if (mod && mod.__esModule)
return mod;
var result = {};
if (mod != null)
for (var k = ownKeys(mod), i = 0; i < k.length; i++)
if (k[i] !== "default")
__createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m")
throw new TypeError("Private method is not writable");
if (kind === "a" && !f)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
function __classPrivateFieldIn(state, receiver) {
if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function"))
throw new TypeError("Cannot use 'in' operator on non-object");
return typeof state === "function" ? receiver === state : state.has(receiver);
}
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function")
throw new TypeError("Object expected.");
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose)
throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose)
throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async)
inner = dispose;
}
if (typeof dispose !== "function")
throw new TypeError("Object not disposable.");
if (inner)
dispose = function () { try {
inner.call(this);
}
catch (e) {
return Promise.reject(e);
} };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
}
var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
function __disposeResources(env) {
function fail(e) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (r = env.stack.pop()) {
try {
if (!r.async && s === 1)
return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async)
return s |= 2, Promise.resolve(result).then(next, function (e) { fail(e); return next(); });
}
else
s |= 1;
}
catch (e) {
fail(e);
}
}
if (s === 1)
return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError)
throw env.error;
}
return next();
}
function __rewriteRelativeImportExtension(path, preserveJsx) {
if (typeof path === "string" && /^\.\.?\//.test(path)) {
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
});
}
return path;
}
var tslib_es6 = {
__extends: __extends,
__assign: __assign,
__rest: __rest,
__decorate: __decorate,
__param: __param,
__esDecorate: __esDecorate,
__runInitializers: __runInitializers,
__propKey: __propKey,
__setFunctionName: __setFunctionName,
__metadata: __metadata,
__awaiter: __awaiter,
__generator: __generator,
__createBinding: __createBinding,
__exportStar: __exportStar,
__values: __values,
__read: __read,
__spread: __spread,
__spreadArrays: __spreadArrays,
__spreadArray: __spreadArray,
__await: __await,
__asyncGenerator: __asyncGenerator,
__asyncDelegator: __asyncDelegator,
__asyncValues: __asyncValues,
__makeTemplateObject: __makeTemplateObject,
__importStar: __importStar,
__importDefault: __importDefault,
__classPrivateFieldGet: __classPrivateFieldGet,
__classPrivateFieldSet: __classPrivateFieldSet,
__classPrivateFieldIn: __classPrivateFieldIn,
__addDisposableResource: __addDisposableResource,
__disposeResources: __disposeResources,
__rewriteRelativeImportExtension: __rewriteRelativeImportExtension,
};
/**
* 📊 SISTEMA DE LOGS DE PERFORMANCE
*
* Sistema completo de monitoramento de performance para aplicações Angular
* com feedback visual através de emojis e relatórios automáticos.
*
* Características:
* - 📈 Monitoramento em Tempo Real
* - 🟢🟡🔴 Classificação Visual por Performance
* - ⏰ Relatórios Automáticos após Inatividade
* - 📊 Análise Detalhada com Recomendações
* - 🛠️ API Pública para Controle Manual
*
* @author Pedro Henrique dos Santos Leuchs
* @version 1.0.19
* @since 2025-07-11
*/
var LogsPerformatico = /** @class */ (function () {
// 🆕 Adiciona requests para registrar requisições HTTP
function LogsPerformatico(serviceName) {
if (serviceName === void 0) { serviceName = 'Service'; }
this.monitoramentoAtivo = true; // Começa ativo na primeira vez
// 📊 Propriedades do Sistema
this.performanceTimers = new Map();
this.performanceSummary = new Map();
this.httpRequests = new Map();
// 🆕 Stack para contexto de função monitorada
this.functionContextStack = [];
this.serviceName = serviceName;
}
/**
* Registra requisição HTTP associando à função monitorada ativa (se houver)
* @param payload Dados da requisição
*/
LogsPerformatico.prototype.registerHttpRequest = function (authReq, tempo, error) {
if (error === void 0) { error = false; }
var _a, _b;
var nome = ((_a = authReq.body) === null || _a === void 0 ? void 0 : _a.name) ||
this.extrairNomeDeSQL((_b = authReq.body) === null || _b === void 0 ? void 0 : _b.sqlInstruction) ||
'(desconhecido)';
var atual = this.httpRequests.get(nome) || {
tempoTotal: 0,
execucoes: 0,
errors: 0,
};
atual.tempoTotal += tempo;
atual.execucoes += 1;
if (error)
atual.errors += 1;
this.httpRequests.set(nome, atual);
};
// Função auxiliar para extrair nome da função de um SQL, ex: PACK_PARMGEN.CONSULTA_PARAMETRO(...)
LogsPerformatico.prototype.extrairNomeDeSQL = function (sql) {
if (!sql)
return null;
var match = sql.match(/([A-Z0-9_]+\.[A-Z0-9_]+)/i);
return match ? match[1] : null;
};
/**
* 🚀 Mensagem de boas-vindas do sistema
*/
LogsPerformatico.prototype.showWelcomeMessage = function () {
console.log("%cSISTEMA DE MONITORAMENTO DE PERFORMANCE", 'color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;');
};
/**
* ⏱️ Inicia cronômetro para uma operação
* @param operationName Nome da operação a ser monitorada
*/
LogsPerformatico.prototype.startTimer = function (operationName) {
if (!this.monitoramentoAtivo)
return;
// Se for a primeira operação, abre borda visual
if (this.performanceTimers.size === 0 &&
this.performanceSummary.size === 0) {
var border = '═'.repeat(56);
console.log("%cIN\u00CDCIO DO MONITORAMENTO DE PERFORMANCE", 'color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;');
}
this.performanceTimers.set(operationName, Date.now());
// Empilha contexto de função monitorada
this.functionContextStack.push(operationName);
console.log("\u2551 [IN\u00CDCIO] " + operationName + " - " + new Date().toLocaleTimeString());
};
/**
* 🏁 Finaliza cronômetro e exibe resultado com emoji
* @param operationName Nome da operação
* @param customMessage Mensagem customizada opcional (ex: para erros)
* @param customThresholds Thresholds customizados para esta operação específica
*/
LogsPerformatico.prototype.endTimer = function (operationName, customMessage, customThresholds) {
var _a, _b;
if (!this.monitoramentoAtivo)
return;
var startTime = this.performanceTimers.get(operationName);
if (!startTime) {
console.warn("\u26A0\uFE0F Timer n\u00E3o encontrado para: " + operationName);
return;
}
var elapsedTime = Date.now() - startTime;
this.performanceTimers.delete(operationName);
// Desempilha contexto de função monitorada
if (this.functionContextStack[this.functionContextStack.length - 1] ===
operationName) {
this.functionContextStack.pop();
}
// Determina status baseado no tempo (com thresholds customizados se fornecidos ou dinâmicos)
var _d = this.getPerformanceStatus(elapsedTime, customThresholds, operationName), emoji = _d.emoji, status = _d.status, color = _d.color;
// Log com emoji e cor (com mensagem customizada se fornecida)
var message = customMessage
? operationName + " - " + customMessage
: "" + operationName;
var fixedStatus = ("[" + status + "]").padEnd(5); // Ex: '[OK] '
var fixedMessage = message.padEnd(10); // Nome da função
var fixedTime = elapsedTime.toString().padStart(5); // 5 para " 16ms", "2193ms"
console.log("\u2551 %c" + emoji + " " + fixedStatus + " " + fixedMessage + " - " + fixedTime + "ms ", color);
// Mostra thresholds customizados se estiverem sendo usados
if (customThresholds &&
(customThresholds.ok ||
customThresholds.lento ||
customThresholds.critico)) {
console.log("\u2699\uFE0F Thresholds customizados: OK<" + ((_a = customThresholds.ok) !== null && _a !== void 0 ? _a : 500) + "ms, LENTO<" + ((_b = customThresholds.lento) !== null && _b !== void 0 ? _b : 2000) + "ms");
}
// Atualiza sumário (com thresholds customizados se fornecidos)
this.updatePerformanceSummary(operationName, elapsedTime, customThresholds);
};
/**
* 🎨 Determina status de performance baseado no tempo
* @param elapsedTime Tempo decorrido em milissegundos
* @param customThresholds Thresholds customizados para esta operação específica
* @param operationName Nome da operação (para calcular thresholds dinâmicos)
* @returns Objeto com emoji, status e cor
*/
LogsPerformatico.prototype.getPerformanceStatus = function (elapsedTime, customThresholds, operationName) {
var _a, _b, _c;
var okThreshold;
var lentoThreshold;
var criticoThreshold;
if (customThresholds &&
(customThresholds.ok ||
customThresholds.lento ||
customThresholds.critico)) {
// Usa thresholds customizados se fornecidos
okThreshold = (_a = customThresholds.ok) !== null && _a !== void 0 ? _a : 500;
lentoThreshold = (_b = customThresholds.lento) !== null && _b !== void 0 ? _b : 2000;
criticoThreshold = (_c = customThresholds.critico) !== null && _c !== void 0 ? _c : Number.MAX_SAFE_INTEGER;
}
else if (operationName) {
// Calcula thresholds dinâmicos baseados na quantidade de execuções
var stats = this.performanceSummary.get(operationName);
// Corrige: soma +1 para considerar a execução atual
var executionCount = stats ? stats.count + 1 : 1;
var dynamicThresholds = this.calculateDynamicThresholds(executionCount);
okThreshold = dynamicThresholds.ok;
lentoThreshold = dynamicThresholds.lento;
criticoThreshold = dynamicThresholds.critico;
}
else {
// Usa thresholds padrões
okThreshold = 500;
lentoThreshold = 2000;
criticoThreshold = Number.MAX_SAFE_INTEGER;
}
if (elapsedTime < okThreshold) {
return {
emoji: '🟢',
status: 'OK',
color: 'color: green; font-weight: bold;',
};
}
else if (elapsedTime < lentoThreshold) {
return {
emoji: '🟡',
status: 'LENTO',
color: 'color: orange; font-weight: bold;',
};
}
else {
return {
emoji: '🔴',
status: 'CRÍTICO',
color: 'color: red; font-weight: bold;',
};
}
};
/**
* 📈 Atualiza estatísticas de performance para o sumário
* @param operationName Nome da operação
* @param elapsedTime Tempo decorrido em milissegundos
* @param customThresholds Thresholds customizados para armazenar (opcional)
*/
LogsPerformatico.prototype.updatePerformanceSummary = function (operationName, elapsedTime, customThresholds) {
var existing = this.performanceSummary.get(operationName);
if (existing) {
existing.count++;
existing.totalTime += elapsedTime;
existing.minTime = Math.min(existing.minTime, elapsedTime);
existing.maxTime = Math.max(existing.maxTime, elapsedTime);
// Atualiza thresholds customizados se fornecidos
if (customThresholds &&
(customThresholds.ok ||
customThresholds.lento ||
customThresholds.critico)) {
existing.customThresholds = customThresholds;
}
}
else {
this.performanceSummary.set(operationName, {
count: 1,
totalTime: elapsedTime,
minTime: elapsedTime,
maxTime: elapsedTime,
customThresholds: customThresholds,
});
}
// Não faz mais nada aqui, relatório só manual
};
/**
* 📊 Exibe relatório resumido de todas as operações (compactado)
*/
LogsPerformatico.prototype.showPerformanceSummary = function (showFullDetails) {
var _this = this;
if (showFullDetails === void 0) { showFullDetails = false; }
// Fecha borda do monitoramento ao gerar relatório
console.log('%c RELATÓRIO DE PERFORMANCE', 'color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;');
if (this.performanceSummary.size === 0) {
console.log('%c Nenhuma operação monitorada ainda.', 'color: gray; font-style: italic;');
return;
}
var sortedEntries = Array.from(this.performanceSummary.entries()).sort(function (a, b) { return b[1].maxTime - a[1].maxTime; });
var table = Object.fromEntries(sortedEntries.map(function (_d) {
var _e = __read(_d, 2), operation = _e[0], stats = _e[1];
var avgTime = Math.round(stats.totalTime / stats.count);
var _f = _this.getPerformanceStatus(avgTime, stats.customThresholds, operation), emoji = _f.emoji, status = _f.status;
return [
operation,
{
Execuções: stats.count,
Média: (avgTime + "ms (" + status + ") " + emoji).trim(),
Mínimo: stats.minTime + "ms",
Máximo: stats.maxTime + "ms",
Total: stats.totalTime + "ms",
},
];
}));
console.table(table);
// Removido: agora a análise detalhada é chamada apenas pelo botão
};
/**
* 📑 Exibe relatório detalhado de requisições HTTP agrupadas por função
*/
LogsPerformatico.prototype.showHttpRequestsReport = function () {
console.log("%cRELAT\u00D3RIO DETALHADO DE REQUISI\u00C7\u00D5ES HTTP", 'color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;');
if (this.httpRequests.size === 0) {
console.log('Nenhuma requisição HTTP registrada.');
return;
}
var tabela = Object.fromEntries(Array.from(this.httpRequests.entries())
.sort(function (a, b) { return b[1].tempoTotal - a[1].tempoTotal; })
.map(function (_d) {
var _e = __read(_d, 2), nome = _e[0], dados = _e[1];
return [
nome,
{
Execuções: dados.execucoes,
Média: Math.round(dados.tempoTotal / dados.execucoes) + "ms",
'Tempo Total': Math.round(dados.tempoTotal) + "ms",
Erros: dados.errors,
},
];
}));
console.table(tabela);
};
/**
* 🔍 Gera análise detalhada de performance
*/
LogsPerformatico.prototype.generateDetailedAnalysis = function () {
var _this = this;
// Título discreto
console.log('%cANÁLISE DETALHADA DE PERFORMANCE', 'color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;');
console.log('');
if (this.performanceSummary.size === 0) {
console.log('%cNenhuma operação registrada para análise.', 'color: #bbb; font-style: italic; font-size: 14px; padding: 4px 0 4px 10px;');
return;
}
var _d = this.categorizeOperations(), criticalOperations = _d.criticalOperations, slowOperations = _d.slowOperations, fastOperations = _d.fastOperations;
// Helper para bloco discreto com texto claro
var printBlock = function (color, emoji, operation, avg, extra) {
var style = "border-left: 4px solid " + color + "; padding: 2px 0 2px 10px; margin: 2px 0 2px 0; font-size: 14px; color: #fff; background: none; font-weight: normal;";
console.log(("%c" + emoji + " " + operation + " - " + avg + "ms (m\u00E9dia) " + extra).trim(), style);
};
if (criticalOperations.length > 0) {
console.log('%c🔴 CRÍTICAS ( > 2000ms)', 'color: #fff; font-size: 14px; font-weight: bold; margin-top: 10px;');
criticalOperations.forEach(function (_d) {
var _e = __read(_d, 2), operation = _e[0], stats = _e[1];
var avg = Math.round(stats.totalTime / stats.count);
var emoji = _this.getPerformanceStatus(avg, stats.customThresholds, operation).emoji;
printBlock('#c53030', emoji, operation, avg, '| otimizar urgente');
});
}
if (slowOperations.length > 0) {
console.log('%c🟡 LENTAS (500ms - 2000ms)', 'color: #fff; font-size: 14px; font-weight: bold; margin-top: 10px;');
slowOperations.forEach(function (_d) {
var _e = __read(_d, 2), operation = _e[0], stats = _e[1];
var avg = Math.round(stats.totalTime / stats.count);
var emoji = _this.getPerformanceStatus(avg, stats.customThresholds, operation).emoji;
printBlock('#b7791f', emoji, operation, avg, '| pode ser melhorada');
});
}
if (fastOperations.length > 0) {
console.log('%c🟢 RÁPIDAS ( < 500ms)', 'color: #fff; font-size: 14px; font-weight: bold; margin-top: 10px;');
fastOperations.forEach(function (_d) {
var _e = __read(_d, 2), operation = _e[0], stats = _e[1];
var avg = Math.round(stats.totalTime / stats.count);
var emoji = _this.getPerformanceStatus(avg, stats.customThresholds, operation).emoji;
printBlock('#38a169', emoji, operation, avg, '| excelente');
});
}
// Recomendações
console.log('%cRecomendações:', 'color: #fff; font-size: 13px; font-weight: bold; margin-top: 14px; padding: 2px 0 2px 0;');
if (criticalOperations.length > 0) {
console.log('%c• Priorize a otimização das operações críticas.', 'color: #fff; font-size: 13px; font-weight: normal;');
console.log('%c• Considere implementar cache ou otimizar consultas SQL para essas operações.', 'color: #fff; font-size: 13px; font-weight: normal;');
}
if (slowOperations.length > 0) {
console.log('%c• Operações lentas podem se beneficiar de índices no banco de dados.', 'color: #fff; font-size: 13px; font-weight: normal;');
}
if (criticalOperations.length === 0 && slowOperations.length === 0) {
console.log('%c• Todas as operações estão com performance excelente!', 'color: #fff; font-size: 13px; font-weight: normal;');
}
// Score
var totalOperations = this.performanceSummary.size;
var fastCount = fastOperations.length;
var performanceScore = totalOperations > 0
? Math.round((fastCount / totalOperations) * 100)
: 100;
var scoreColor = performanceScore >= 80
? '#38a169'
: performanceScore >= 60
? '#f6e05e'
: '#c53030';
var scoreMsg = performanceScore >= 80
? 'Excelente! A maioria das operações está performando bem.'
: performanceScore >= 60
? 'Médio. Há espaço para melhorias de performance.'
: 'Crítico. Muitas operações precisam de otimização urgente.';
console.log("%cScore de performance: " + performanceScore + "%", "color: #fff; background: " + scoreColor + "; font-size: 14px; font-weight: bold; margin-top: 10px; padding: 2px 8px; border-radius: 3px;");
console.log("%c" + scoreMsg, "color: #fff; font-size: 13px; font-weight: normal; margin-bottom: 8px;");
console.log('');
};
/**
* 📋 Categoriza operações por performance
* @returns Objeto com arrays de operações categorizadas
*/
LogsPerformatico.prototype.categorizeOperations = function () {
var criticalOperations = Array.from(this.performanceSummary.entries()).filter(function (_d) {
var _e = __read(_d, 2), _ = _e[0], stats = _e[1];
return stats.totalTime / stats.count > 2000;
});
var slowOperations = Array.from(this.performanceSummary.entries()).filter(function (_d) {
var _e = __read(_d, 2), _ = _e[0], stats = _e[1];
var avg = stats.totalTime / stats.count;
return avg >= 500 && avg <= 2000;
});
var fastOperations = Array.from(this.performanceSummary.entries()).filter(function (_d) {
var _e = __read(_d, 2), _ = _e[0], stats = _e[1];
return stats.totalTime / stats.count < 500;
});
return { criticalOperations: criticalOperations, slowOperations: slowOperations, fastOperations: fastOperations };
};
/**
* 💡 Exibe recomendações baseadas na análise
* @param criticalOperations Array de operações críticas
* @param slowOperations Array de operações lentas
*/
LogsPerformatico.prototype.showRecommendations = function (criticalOperations, slowOperations) {
console.log('RECOMENDAÇÕES:');
if (criticalOperations.length > 0) {
console.log(' Priorize a otimização das operações críticas.');
console.log(' Considere implementar cache ou otimizar consultas SQL para essas operações.');
}
if (slowOperations.length > 0) {
console.log(' Operações lentas podem se beneficiar de índices no banco de dados.');
}
if (criticalOperations.length === 0 && slowOperations.length === 0) {
console.log(' Todas as operações estão com performance excelente!');
}
};
/**
* 📊 Exibe score de performance
* @param fastOperationsCount Número de operações rápidas
*/
LogsPerformatico.prototype.showPerformanceScore = function (fastOperationsCount) {
var totalOperations = this.performanceSummary.size;
var performanceScore = Math.round((fastOperationsCount / totalOperations) * 100);
console.log("SCORE DE PERFORMANCE: " + performanceScore + "%");
if (performanceScore >= 80) {
console.log('Excelente! A maioria das operações está performando bem.');
}
else if (performanceScore >= 60) {
console.log('Médio. Há espaço para melhorias de performance.');
}
else {
console.log('Crítico. Muitas operações precisam de otimização urgente.');
}
};
// ===== API PÚBLICA =====
/**
* 📊 Método público para exibir relatório de performance
* Pode ser chamado no console do navegador para análise
*/
LogsPerformatico.prototype.getPerformanceReport = function () {
this.showPerformanceSummary();
};
/**
* 🧹 Método público para limpar dados de performance
* Útil para resetar estatísticas e começar nova análise
*/
LogsPerformatico.prototype.resetPerformanceData = function () {
this.performanceTimers.clear();
this.performanceSummary.clear();
this.httpRequests.clear();
// Mensagem estilizada de limpeza
console.log('%c🧹 [CLEANUP] Dados de performance limpos', 'color: #fff; background: #43248bff; font-size: 13px; font-weight: bold; border-radius: 4px; padding: 4px 12px; margin: 6px 0;');
};
/**
* ⏰ Configura o delay para relatório por inatividade
* @param seconds Número de segundos de inatividade para mostrar relatório
*/
LogsPerformatico.prototype.setInactivityDelay = function (seconds) {
// Desabilitado
console.log('⏰ Relatório por inatividade está desabilitado.');
};
/**
* 🔇 Desabilita relatório automático por inatividade
*/
LogsPerformatico.prototype.disableInactivityReport = function () {
// Desabilitado
console.log('🔇 Relatório por inatividade já está desabilitado');
};
/**
* ⚙️ Configura o threshold para relatório automático
* @param threshold Número de operações para mostrar relatório automaticamente
*/
LogsPerformatico.prototype.setAutoReportThreshold = function (threshold) {
// Desabilitado
console.log('⚙️ Threshold para relatório automático está desabilitado.');
};
/**
* 🔇 Desabilita relatório automático
*/
LogsPerformatico.prototype.disableAutoReport = function () {
// Desabilitado
console.log('🔇 Relatório automático desabilitado');
};
/**
* 📈 Obtém estatísticas resumidas sem exibir no console
* @returns Objeto com estatísticas de performance
*/
LogsPerformatico.prototype.getStatistics = function () {
var _d = this.categorizeOperations(), criticalOperations = _d.criticalOperations, slowOperations = _d.slowOperations, fastOperations = _d.fastOperations;
var totalOperations = this.performanceSummary.size;
var totalTime = 0;
var totalCount = 0;
this.performanceSummary.forEach(function (stats) {
totalTime += stats.totalTime;
totalCount += stats.count;
});
var averageTime = totalCount > 0 ? Math.round(totalTime / totalCount) : 0;
var performanceScore = totalOperations > 0
? Math.round((fastOperations.length / totalOperations) * 100)
: 100;
return {
totalOperations: totalOperations,
averageTime: averageTime,
fastOperations: fastOperations.length,
slowOperations: slowOperations.length,
criticalOperations: criticalOperations.length,
performanceScore: performanceScore,
};
};
/**
* 🎯 Obtém dados de uma operação específica
* @param operationName Nome da operação
* @returns Estatísticas da operação ou null se não encontrada
*/
LogsPerformatico.prototype.getOperationStats = function (operationName) {
var baseStats = this.performanceSummary.get(operationName);
if (!baseStats)
return null;
// Extrai nomes das requisições HTTP como array de strings
var httpRequestEntry = this.httpRequests.get(operationName);
var httpCalls = httpRequestEntry ? [operationName] : [];
return Object.assign(Object.assign({}, baseStats), { httpCalls: httpCalls });
};
/**
* 📋 Lista todas as operações monitoradas
* @returns Array com nomes das operações
*/
LogsPerformatico.prototype.getMonitoredOperations = function () {
return Array.from(this.performanceSummary.keys());
};
/**
* 🔄 Verifica se há timers ativos
* @returns true se há timers em execução
*/
LogsPerformatico.prototype.hasActiveTimers = function () {
return this.performanceTimers.size > 0;
};
/**
* 🗑️ Limpa apenas os timers ativos (não as estatísticas)
*/
LogsPerformatico.prototype.clearActiveTimers = function () {
this.performanceTimers.clear();
console.log('%c🗑️ [CLEANUP] Timers ativos limpos', 'color: #fff; background: #23272f; font-size: 13px; font-weight: bold; border-radius: 4px; padding: 4px 12px; margin: 6px 0;');
};
/**
* 💾 Exporta dados de performance para JSON
* @returns String JSON com todos os dados
*/
LogsPerformatico.prototype.exportData = function () {
var data = {
timestamp: new Date().toISOString(),
serviceName: this.serviceName,
statistics: this.getStatistics(),
operations: Array.from(this.performanceSummary.entries()).map(function (_d) {
var _e = __read(_d, 2), name = _e[0], stats = _e[1];
return (Object.assign(Object.assign({ name: name }, stats), { averageTime: Math.round(stats.totalTime / stats.count) }));
}),
};
return JSON.stringify(data, null, 2);
};
/**
* 🎯 Calcula thresholds dinâmicos baseados na quantidade de execuções
* @param executionCount Número de execuções da operação
* @returns Objeto com thresholds calculados dinamicamente
*/
LogsPerformatico.prototype.calculateDynamicThresholds = function (executionCount) {
if (executionCount === 1) {
// Primeira execução - expectativas mais relaxadas
return {
ok: 1000,
lento: 2000,
critico: 2000,
};
}
else if (executionCount <= 5) {
// Até 5 execuções - sistema ainda aquecendo
return {
ok: 500,
lento: 1000,
critico: 1000,
};
}
else if (executionCount <= 10) {
// Até 10 execuções - sistema otimizado
return {
ok: 100,
lento: 250,
critico: 250,
};
}
else {
// Acima de 10 execuções - expectativas altas
return {
ok: 20,
lento: 60,
critico: 60,
};
}
};
LogsPerformatico.prototype.injectMonitorButton = function () {
var _this = this;
if (document.getElementById('btn-monitorar-performance'))
return;
// ====== ESTILO MODERNO E BOTÃO DE OLHO ======
var BUTTON_COLOR = '#23272f'; // cinza escuro elegante
var BUTTON_TEXT_COLOR = '#f3f4f6';
var BUTTON_RADIUS = '8px';
var BUTTON_FONT_SIZE = '13px';
var BUTTON_PADDING = '10px 5px';
var BUTTON_WIDTH = '210px';
var BUTTON_HEIGHT = '44px';
var BUTTON_BOX_SHADOW = '0 2px 12px #0002';
var BUTTON_BORDER = '1px solid #353a40';
// Container para animação
var container = document.createElement('div');
container.id = 'performance-monitor-container';
Object.assign(container.style, {
position: 'fixed',
bottom: '5px',
left: '50px',
zIndex: '9999',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'flex-end',
transition: 'transform 0.5s cubic-bezier(.4,2,.6,1)',
gap: '10px',
});
// Função para criar botões padronizados
var criarBotao = function (id, texto) {
var btn = document.createElement('button');
btn.id = id;
btn.innerText = texto;
Object.assign(btn.style, {
width: BUTTON_WIDTH,
height: BUTTON_HEIGHT,
background: BUTTON_COLOR,
color: BUTTON_TEXT_COLOR,
borderRadius: BUTTON_RADIUS,
border: BUTTON_BORDER,
padding: BUTTON_PADDING,
fontSize: BUTTON_FONT_SIZE,
fontWeight: '600',
cursor: 'pointer',
boxShadow: BUTTON_BOX_SHADOW,
letterSpacing: '0.01em',
textAlign: 'center',
transition: 'background 0.2s, color 0.2s, transform 0.5s cubic-bezier(.4,2,.6,1)',
});
btn.onmouseenter = function () {
btn.style.background = '#353a40';
btn.style.color = '#fff';
};
btn.onmouseleave = function () {
btn.style.background = BUTTON_COLOR;
btn.style.color = BUTTON_TEXT_COLOR;
};
return btn;
};
// Botões principais
var btnMain = criarBotao('btn-monitorar-performance', 'Parar monitoramento');
var btnFinalizar = criarBotao('btn-finalizar-monitoramento', 'Finalizar monitoramento');
var btnRequisicoesDetalhadas = criarBotao('btn-req-detalhadas-performance', 'Requisições detalhadas');
var btnAnaliseDetalhada = criarBotao('btn-analise-detalhada-performance', 'Análise detalhada');
// Inicialmente escondidos
btnRequisicoesDetalhadas.style.display = 'none';
btnAnaliseDetalhada.style.display = 'none';
btnFinalizar.style.display = 'none';
// Botão de esconder/mostrar com ícone de olho (fora do container)
var btnToggle = document.createElement('button');
btnToggle.id = 'btn-toggle-performance';
btnToggle.innerHTML = "\n <img\n src=\"https://cdn-icons-png.flaticon.com/512/565/565655.png\"\n alt=\"esconder\"\n style=\"width:15px; height:15px; vertical-align:middle; filter: invert(1);\"\n />\n ";
Object.assign(btnToggle.style, {
width: '38px',
height: '38px',
background: '#23272f',
color: '#f3f4f6',
borderRadius: '50%',
border: BUTTON_BORDER,
fontSize: '20px',
fontWeight: 'bold',
cursor: 'pointer',
boxShadow: BUTTON_BOX_SHADOW,
position: 'fixed',
left: '5px',
bottom: '5px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: '10000',
});
btnToggle.onmouseenter = function () {
btnToggle.style.background = '#353a40';
btnToggle.style.color = '#fff';
};
btnToggle.onmouseleave = function () {
btnToggle.style.background = '#23272f';
btnToggle.style.color = '#f3f4f6';
};
var hidden = false;
btnToggle.onclick = function () {
hidden = !hidden;
if (hidden) {
container.style.display = 'none';
btnToggle.innerHTML = "\n <img\n src=\"https://cdn-icons-png.flaticon.com/512/159/159604.png\"\n alt=\"mostrar\"\n style=\"width:15px; height:15px; vertical-align:middle; filter: invert(1);\"\n />\n ";
}
else {
container.style.display = 'flex';
btnToggle.innerHTML = "\n <img\n src=\"https://cdn-icons-png.flaticon.com/512/565/565655.png\"\n alt=\"esconder\"\n style=\"width:15px; height:15px; vertical-align:middle; filter: invert(1);\"\n />\n ";
}
};
// Estado dos botões
var estado = 'monitorando';
var atualizarBotoes = function (novoEstado) {
estado = novoEstado;
switch (estado) {
case 'inativo':
btnMain.innerText = 'Iniciar monitoramento';
_this.monitoramentoAtivo = false;
btnFinalizar.style.display = 'none';
btnRequisicoesDetalhadas.style.display = 'none';
btnAnaliseDetalhada.style.display = 'none';
break;
case 'monitorando':
btnMain.innerText = 'Parar monitoramento';
_this.monitoramentoAtivo = true;
btnFinalizar.style.display = 'none';
btnRequisicoesDetalhadas.style.display = 'none';
btnAnaliseDetalhada.style.display = 'none';
break;
case 'relatorio':
btnMain.innerText = 'Gerar relatório';
_this.monitoramentoAtivo = false;
btnFinalizar.style.display = 'none';
btnRequisicoesDetalhadas.style.display = 'block';
btnAnaliseDetalhada.style.display = 'block';
break;
case 'relatorio_gerado':
btnMain.innerText = 'Gerar relatório';
_this.monitoramentoAtivo = false;
btnFinalizar.style.display = 'block';
btnRequisicoesDetalhadas.style.display = 'block';
btnAnaliseDetalhada.style.display = 'block';
break;
}
};
// Ações dos botões
btnMain.onclick = function () {
if (estado === 'inativo') {
_this.resetPerformanceData();
_this.showWelcomeMessage();
atualizarBotoes('monitorando');
}
else if (estado === 'monitorando') {
atualizarBotoes('relatorio');
}
else if (estado === 'relatorio' || estado === 'relatorio_gerado') {
_this.showPerformanceSummary(false);
atualizarBotoes('relatorio_gerado');
}
};
btnFinalizar.onclick = function () {
_this.resetPerformanceData();
atualizarBotoes('inativo');
};
// Apêndice
this.showWelcomeMessage();
container.appendChild(btnMain);
container.appendChild(btnRequisicoesDetalhadas);
container.appendChild(btnAnaliseDetalhada);
container.appendChild(btnFinalizar);
document.body.appendChild(container);
document.body.appendChild(btnToggle);
// Ação do botão de requisições detalhadas
btnRequisicoesDetalhadas.onclick = function () {
_this.showHttpRequestsReport();
};
// Ação do botão de análise detalhada
btnAnaliseDetalhada.onclick = function () {
_this.generateDetailedAnalysis();
};
};
return LogsPerformatico;
}());
/**
* 🏭 Factory function para criar instância do LogsPerformatico
* @param serviceName Nome do serviço (para logs personalizados)
* @returns Nova instância de LogsPerformatico
*/
function createPerformanceLogger(serviceName) {
if (serviceName === void 0) { serviceName = 'Service'; }
return new LogsPerformatico(serviceName);
}
var GlobalPerformanceLogger = createPerformanceLogger('GLOBAL');
var PerformanceMonitor = PerformanceMonitorFactory(GlobalPerformanceLogger);
function PerformanceMonitorFactory(globalLogger) {
return function PerformanceMonitor(options) {
return function (target, propertyKey, descriptor) {
var originalMethod = descriptor.value;
var opName;
var customMethod;
var customThresholds;
if (typeof options === 'object' && options !== null) {
opName = options.name || propertyKey;
customMethod = options.method;
customThresholds = {
ok: options.ok,
lento: options.lento,
critico: options.critico,
};
}
else if (typeof options === 'function') {
opName = options.name || propertyKey;
customMethod = options;
}
else if (typeof options === 'string') {
opName = options;
}
else {
opName = propertyKey;
}
descriptor.value = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return __awaiter(this, void 0, void 0, function () {
var instanceLogger, logger, methodToCall, result, methodToCall;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
instanceLogger = this
.performanceLogger;
logger = instanceLogger || globalLogger;
if (!logger) return [3 /*break*/, 5];
logger.startTimer(opName);
_a.label = 1;
case 1:
_a.trys.push([1, , 3, 4]);
methodToCall = customMethod || originalMethod;
return [4 /*yield*/, methodToCall.apply(this, args)];
case 2:
result = _a.sent();
return [2 /*return*/, result];
case 3:
logger.endTimer(opName, undefined, customThresholds);
return [7 /*endfinally*/];
case 4: return [3 /*break*/, 7];
case 5:
methodToCall = customMethod || originalMethod;
return [4 /*yield*/, methodToCall.apply(this, args)];
case 6: return [2 /*return*/, _a.sent()];
case 7: return [2 /*return*/];
}
});
});
};
return descriptor;
};
};
}
var PerformanceMonitorInterceptor = /** @class */ (function () {
function PerformanceMonitorInterceptor() {
}
PerformanceMonitorInterceptor.prototype.intercept = function (req, next) {
var _a;
// Ignora arquivos de assets
if (!req.url.startsWith('./assets')) {
// 🔹 Recupera dados da sessão
var tela = sessionStorage.getItem('idTela');
if (!tela) {
tela = 'SEL041';
sessionStorage.setItem('idTela', tela);
}
var cdUsuario = (_a = sessionStorage.getItem('cdUsuario')) !== null && _a !== void 0 ? _a : '';
// 🔹 Clona a requisição adicionando headers
var authReq_1 = req.clone({
headers: req.headers
.set('tela_id', tela)
.set('tela', 'SEL041')
.set('user', cdUsuario),
});
var start_1 = performance.now();
return next.handle(authReq_1).pipe(operators.tap({
next: function (event) {
var _a, _b;
if (event instanceof http.HttpResponse) {
var tempo = performance.now() - start_1;
// ✅ Verificação segura do body e suas propriedades
var operationType = ((_a = authReq_1.body) === null || _a === void 0 ? void 0 : _a.operationType) || 'UNKNOWN';
var operationName = ((_b = authReq_1.body) === null || _b === void 0 ? void 0 : _b.name) || '';
console.log("%c\uD83D\uDFE2 [HTTP] " + operationType + " " + (operationType === 'SELECT_FULL' ? '' : operationName) + " - " + tempo.toFixed(1) + "ms", 'color: #6cbbd8ff; font-weight: bold;');
GlobalPerformanceLogger.registerHttpRequest(authReq_1, tempo, false);
}
},
error: function (error) {
var _a, _b;
var tempo = performance.now() - start_1;
// ✅ Verificação segura do body e suas propriedades
var operationType = ((_a = authReq_1.body) === null || _a === void 0 ? void 0 : _a.operationType) || 'UNKNOWN';
var operationName = ((_b = authReq_1.body) === null || _b === void 0 ? void 0 : _b.name) || '';
console.groupCollapsed("%c\uD83D\uDD34 [HTTP] " + operationType + " " + operationName + " - " + tempo.toFixed(1) + "ms", 'color: #6cbbd8ff; font-weight: bold;');
console.error(error);
console.groupEnd();
GlobalPerformanceLogger.registerHttpRequest(authReq_1, tempo, true);
},
}));
}
// Requisição de asset, passa direto
return next.handle(req);
};
return PerformanceMonitorInterceptor;
}());
PerformanceMonitorInterceptor.decorators = [
{ type: i0.Injectable }
];
/*
* Public API Surface of performance-monitor
*/
/**
* Generated bundle index. Do not edit.
*/
exports.GlobalPerformanceLogger = GlobalPerformanceLogger;
exports.PerformanceMonitor = PerformanceMonitor;
exports.PerformanceMonitorComponent = PerformanceMonitorComponent;
exports.PerformanceMonitorInterceptor = PerformanceMonitorInterceptor;
exports.PerformanceMonitorModule = PerformanceMonitorModule;
exports.PerformanceMonitorService = PerformanceMonitorService;
exports.ɵa = LogsPerformatico;
exports.ɵb = createPerformanceLogger;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=performance-monitor-logger.umd.js.map