UNPKG

performance-monitor-logger

Version:
2 lines 20.5 kB
!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports,require("@angular/core"),require("@angular/common/http"),require("rxjs/operators")):"function"==typeof define&&define.amd?define("performance-monitor-logger",["exports","@angular/core","@angular/common/http","rxjs/operators"],o):o((e="undefined"!=typeof globalThis?globalThis:e||self)["performance-monitor-logger"]={},e.ng.core,e.ng.common.http,e.rxjs.operators)}(this,(function(e,o,t,r){"use strict";var n=function(){function e(){}return e.prototype.ngOnInit=function(){},e}();n.decorators=[{type:o.Component,args:[{selector:"lib-performanceMonitorLogger",template:" <p>performance-monitor-logger works!</p> "}]}],n.ctorParameters=function(){return[]};var i=function(){};i.decorators=[{type:o.NgModule,args:[{declarations:[n],imports:[],exports:[n]}]}];var a=function(){};a.ɵprov=o.ɵɵdefineInjectable({factory:function(){return new a},token:a,providedIn:"root"}),a.decorators=[{type:o.Injectable,args:[{providedIn:"root"}]}],a.ctorParameters=function(){return[]};function s(e,o,t,r){return new(t||(t=Promise))((function(n,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function s(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var o;e.done?n(e.value):(o=e.value,o instanceof t?o:new t((function(e){e(o)}))).then(a,s)}c((r=r.apply(e,o||[])).next())}))}function c(e,o){var t,r,n,i={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(t)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(t=1,r&&(n=2&s[0]?r.return:s[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,s[1])).done)return n;switch(r=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(n=i.trys,(n=n.length>0&&n[n.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]<n[3])){i.label=s[1];break}if(6===s[0]&&i.label<n[1]){i.label=n[1],n=s;break}if(n&&i.label<n[2]){i.label=n[2],i.ops.push(s);break}n[2]&&i.ops.pop(),i.trys.pop();continue}s=o.call(e,i)}catch(e){s=[6,e],r=0}finally{t=n=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}Object.create;function l(e,o){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var r,n,i=t.call(e),a=[];try{for(;(void 0===o||o-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){n={error:e}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(n)throw n.error}}return a}Object.create;"function"==typeof SuppressedError&&SuppressedError;var p=function(){function e(e){void 0===e&&(e="Service"),this.monitoramentoAtivo=!0,this.performanceTimers=new Map,this.performanceSummary=new Map,this.httpRequests=new Map,this.functionContextStack=[],this.serviceName=e}return e.prototype.registerHttpRequest=function(e,o,t){var r,n;void 0===t&&(t=!1);var i=(null===(r=e.body)||void 0===r?void 0:r.name)||this.extrairNomeDeSQL(null===(n=e.body)||void 0===n?void 0:n.sqlInstruction)||"(desconhecido)",a=this.httpRequests.get(i)||{tempoTotal:0,execucoes:0,errors:0};a.tempoTotal+=o,a.execucoes+=1,t&&(a.errors+=1),this.httpRequests.set(i,a)},e.prototype.extrairNomeDeSQL=function(e){if(!e)return null;var o=e.match(/([A-Z0-9_]+\.[A-Z0-9_]+)/i);return o?o[1]:null},e.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;")},e.prototype.startTimer=function(e){if(this.monitoramentoAtivo){if(0===this.performanceTimers.size&&0===this.performanceSummary.size){"═".repeat(56);console.log("%cINÍCIO 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(e,Date.now()),this.functionContextStack.push(e),console.log("║ [INÍCIO] "+e+" - "+(new Date).toLocaleTimeString())}},e.prototype.endTimer=function(e,o,t){var r,n;if(this.monitoramentoAtivo){var i=this.performanceTimers.get(e);if(i){var a=Date.now()-i;this.performanceTimers.delete(e),this.functionContextStack[this.functionContextStack.length-1]===e&&this.functionContextStack.pop();var s=this.getPerformanceStatus(a,t,e),c=s.emoji,l=s.status,p=s.color,f=o?e+" - "+o:""+e,m=("["+l+"]").padEnd(5),u=f.padEnd(10),d=a.toString().padStart(5);console.log("║ %c"+c+" "+m+" "+u+" - "+d+"ms ",p),t&&(t.ok||t.lento||t.critico)&&console.log("⚙️ Thresholds customizados: OK<"+(null!==(r=t.ok)&&void 0!==r?r:500)+"ms, LENTO<"+(null!==(n=t.lento)&&void 0!==n?n:2e3)+"ms"),this.updatePerformanceSummary(e,a,t)}else console.warn("⚠️ Timer não encontrado para: "+e)}},e.prototype.getPerformanceStatus=function(e,o,t){var r,n,i,a,s;if(o&&(o.ok||o.lento||o.critico))a=null!==(r=o.ok)&&void 0!==r?r:500,s=null!==(n=o.lento)&&void 0!==n?n:2e3,null!==(i=o.critico)&&void 0!==i?i:Number.MAX_SAFE_INTEGER;else if(t){var c=this.performanceSummary.get(t),l=c?c.count+1:1,p=this.calculateDynamicThresholds(l);a=p.ok,s=p.lento,p.critico}else a=500,s=2e3,Number.MAX_SAFE_INTEGER;return e<a?{emoji:"🟢",status:"OK",color:"color: green; font-weight: bold;"}:e<s?{emoji:"🟡",status:"LENTO",color:"color: orange; font-weight: bold;"}:{emoji:"🔴",status:"CRÍTICO",color:"color: red; font-weight: bold;"}},e.prototype.updatePerformanceSummary=function(e,o,t){var r=this.performanceSummary.get(e);r?(r.count++,r.totalTime+=o,r.minTime=Math.min(r.minTime,o),r.maxTime=Math.max(r.maxTime,o),t&&(t.ok||t.lento||t.critico)&&(r.customThresholds=t)):this.performanceSummary.set(e,{count:1,totalTime:o,minTime:o,maxTime:o,customThresholds:t})},e.prototype.showPerformanceSummary=function(e){var o=this;if(void 0===e&&(e=!1),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;"),0!==this.performanceSummary.size){var t=Array.from(this.performanceSummary.entries()).sort((function(e,o){return o[1].maxTime-e[1].maxTime})),r=Object.fromEntries(t.map((function(e){var t=l(e,2),r=t[0],n=t[1],i=Math.round(n.totalTime/n.count),a=o.getPerformanceStatus(i,n.customThresholds,r),s=a.emoji,c=a.status;return[r,{"Execuções":n.count,"Média":(i+"ms ("+c+") "+s).trim(),"Mínimo":n.minTime+"ms","Máximo":n.maxTime+"ms",Total:n.totalTime+"ms"}]})));console.table(r)}else console.log("%c Nenhuma operação monitorada ainda.","color: gray; font-style: italic;")},e.prototype.showHttpRequestsReport=function(){if(console.log("%cRELATÓRIO DETALHADO DE REQUISIÇÕES HTTP","color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;"),0!==this.httpRequests.size){var e=Object.fromEntries(Array.from(this.httpRequests.entries()).sort((function(e,o){return o[1].tempoTotal-e[1].tempoTotal})).map((function(e){var o=l(e,2),t=o[0],r=o[1];return[t,{"Execuções":r.execucoes,"Média":Math.round(r.tempoTotal/r.execucoes)+"ms","Tempo Total":Math.round(r.tempoTotal)+"ms",Erros:r.errors}]})));console.table(e)}else console.log("Nenhuma requisição HTTP registrada.")},e.prototype.generateDetailedAnalysis=function(){var e=this;if(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(""),0!==this.performanceSummary.size){var o=this.categorizeOperations(),t=o.criticalOperations,r=o.slowOperations,n=o.fastOperations,i=function(e,o,t,r,n){var i="border-left: 4px solid "+e+"; padding: 2px 0 2px 10px; margin: 2px 0 2px 0; font-size: 14px; color: #fff; background: none; font-weight: normal;";console.log(("%c"+o+" "+t+" - "+r+"ms (média) "+n).trim(),i)};t.length>0&&(console.log("%c🔴 CRÍTICAS ( > 2000ms)","color: #fff; font-size: 14px; font-weight: bold; margin-top: 10px;"),t.forEach((function(o){var t=l(o,2),r=t[0],n=t[1],a=Math.round(n.totalTime/n.count),s=e.getPerformanceStatus(a,n.customThresholds,r).emoji;i("#c53030",s,r,a,"| otimizar urgente")}))),r.length>0&&(console.log("%c🟡 LENTAS (500ms - 2000ms)","color: #fff; font-size: 14px; font-weight: bold; margin-top: 10px;"),r.forEach((function(o){var t=l(o,2),r=t[0],n=t[1],a=Math.round(n.totalTime/n.count),s=e.getPerformanceStatus(a,n.customThresholds,r).emoji;i("#b7791f",s,r,a,"| pode ser melhorada")}))),n.length>0&&(console.log("%c🟢 RÁPIDAS ( < 500ms)","color: #fff; font-size: 14px; font-weight: bold; margin-top: 10px;"),n.forEach((function(o){var t=l(o,2),r=t[0],n=t[1],a=Math.round(n.totalTime/n.count),s=e.getPerformanceStatus(a,n.customThresholds,r).emoji;i("#38a169",s,r,a,"| excelente")}))),console.log("%cRecomendações:","color: #fff; font-size: 13px; font-weight: bold; margin-top: 14px; padding: 2px 0 2px 0;"),t.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;")),r.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;"),0===t.length&&0===r.length&&console.log("%c• Todas as operações estão com performance excelente!","color: #fff; font-size: 13px; font-weight: normal;");var a=this.performanceSummary.size,s=n.length,c=a>0?Math.round(s/a*100):100,p=c>=80?"#38a169":c>=60?"#f6e05e":"#c53030",f=c>=80?"Excelente! A maioria das operações está performando bem.":c>=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: "+c+"%","color: #fff; background: "+p+"; font-size: 14px; font-weight: bold; margin-top: 10px; padding: 2px 8px; border-radius: 3px;"),console.log("%c"+f,"color: #fff; font-size: 13px; font-weight: normal; margin-bottom: 8px;"),console.log("")}else console.log("%cNenhuma operação registrada para análise.","color: #bbb; font-style: italic; font-size: 14px; padding: 4px 0 4px 10px;")},e.prototype.categorizeOperations=function(){return{criticalOperations:Array.from(this.performanceSummary.entries()).filter((function(e){var o=l(e,2),t=(o[0],o[1]);return t.totalTime/t.count>2e3})),slowOperations:Array.from(this.performanceSummary.entries()).filter((function(e){var o=l(e,2),t=(o[0],o[1]),r=t.totalTime/t.count;return r>=500&&r<=2e3})),fastOperations:Array.from(this.performanceSummary.entries()).filter((function(e){var o=l(e,2),t=(o[0],o[1]);return t.totalTime/t.count<500}))}},e.prototype.showRecommendations=function(e,o){console.log("RECOMENDAÇÕES:"),e.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.")),o.length>0&&console.log(" Operações lentas podem se beneficiar de índices no banco de dados."),0===e.length&&0===o.length&&console.log(" Todas as operações estão com performance excelente!")},e.prototype.showPerformanceScore=function(e){var o=this.performanceSummary.size,t=Math.round(e/o*100);console.log("SCORE DE PERFORMANCE: "+t+"%"),t>=80?console.log("Excelente! A maioria das operações está performando bem."):t>=60?console.log("Médio. Há espaço para melhorias de performance."):console.log("Crítico. Muitas operações precisam de otimização urgente.")},e.prototype.getPerformanceReport=function(){this.showPerformanceSummary()},e.prototype.resetPerformanceData=function(){this.performanceTimers.clear(),this.performanceSummary.clear(),this.httpRequests.clear(),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;")},e.prototype.setInactivityDelay=function(e){console.log("⏰ Relatório por inatividade está desabilitado.")},e.prototype.disableInactivityReport=function(){console.log("🔇 Relatório por inatividade já está desabilitado")},e.prototype.setAutoReportThreshold=function(e){console.log("⚙️ Threshold para relatório automático está desabilitado.")},e.prototype.disableAutoReport=function(){console.log("🔇 Relatório automático desabilitado")},e.prototype.getStatistics=function(){var e=this.categorizeOperations(),o=e.criticalOperations,t=e.slowOperations,r=e.fastOperations,n=this.performanceSummary.size,i=0,a=0;this.performanceSummary.forEach((function(e){i+=e.totalTime,a+=e.count}));var s=a>0?Math.round(i/a):0,c=n>0?Math.round(r.length/n*100):100;return{totalOperations:n,averageTime:s,fastOperations:r.length,slowOperations:t.length,criticalOperations:o.length,performanceScore:c}},e.prototype.getOperationStats=function(e){var o=this.performanceSummary.get(e);if(!o)return null;var t=this.httpRequests.get(e)?[e]:[];return Object.assign(Object.assign({},o),{httpCalls:t})},e.prototype.getMonitoredOperations=function(){return Array.from(this.performanceSummary.keys())},e.prototype.hasActiveTimers=function(){return this.performanceTimers.size>0},e.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;")},e.prototype.exportData=function(){var e={timestamp:(new Date).toISOString(),serviceName:this.serviceName,statistics:this.getStatistics(),operations:Array.from(this.performanceSummary.entries()).map((function(e){var o=l(e,2),t=o[0],r=o[1];return Object.assign(Object.assign({name:t},r),{averageTime:Math.round(r.totalTime/r.count)})}))};return JSON.stringify(e,null,2)},e.prototype.calculateDynamicThresholds=function(e){return 1===e?{ok:1e3,lento:2e3,critico:2e3}:e<=5?{ok:500,lento:1e3,critico:1e3}:e<=10?{ok:100,lento:250,critico:250}:{ok:20,lento:60,critico:60}},e.prototype.injectMonitorButton=function(){var e=this;if(!document.getElementById("btn-monitorar-performance")){var o="#23272f",t="#f3f4f6",r="0 2px 12px #0002",n="1px solid #353a40",i=document.createElement("div");i.id="performance-monitor-container",Object.assign(i.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"});var a=function(e,i){var a=document.createElement("button");return a.id=e,a.innerText=i,Object.assign(a.style,{width:"210px",height:"44px",background:o,color:t,borderRadius:"8px",border:n,padding:"10px 5px",fontSize:"13px",fontWeight:"600",cursor:"pointer",boxShadow:r,letterSpacing:"0.01em",textAlign:"center",transition:"background 0.2s, color 0.2s, transform 0.5s cubic-bezier(.4,2,.6,1)"}),a.onmouseenter=function(){a.style.background="#353a40",a.style.color="#fff"},a.onmouseleave=function(){a.style.background=o,a.style.color=t},a},s=a("btn-monitorar-performance","Parar monitoramento"),c=a("btn-finalizar-monitoramento","Finalizar monitoramento"),l=a("btn-req-detalhadas-performance","Requisições detalhadas"),p=a("btn-analise-detalhada-performance","Análise detalhada");l.style.display="none",p.style.display="none",c.style.display="none";var f=document.createElement("button");f.id="btn-toggle-performance",f.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(f.style,{width:"38px",height:"38px",background:"#23272f",color:"#f3f4f6",borderRadius:"50%",border:n,fontSize:"20px",fontWeight:"bold",cursor:"pointer",boxShadow:r,position:"fixed",left:"5px",bottom:"5px",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"10000"}),f.onmouseenter=function(){f.style.background="#353a40",f.style.color="#fff"},f.onmouseleave=function(){f.style.background="#23272f",f.style.color="#f3f4f6"};var m=!1;f.onclick=function(){(m=!m)?(i.style.display="none",f.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 '):(i.style.display="flex",f.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 ')};var u="monitorando",d=function(o){switch(u=o){case"inativo":s.innerText="Iniciar monitoramento",e.monitoramentoAtivo=!1,c.style.display="none",l.style.display="none",p.style.display="none";break;case"monitorando":s.innerText="Parar monitoramento",e.monitoramentoAtivo=!0,c.style.display="none",l.style.display="none",p.style.display="none";break;case"relatorio":s.innerText="Gerar relatório",e.monitoramentoAtivo=!1,c.style.display="none",l.style.display="block",p.style.display="block";break;case"relatorio_gerado":s.innerText="Gerar relatório",e.monitoramentoAtivo=!1,c.style.display="block",l.style.display="block",p.style.display="block"}};s.onclick=function(){"inativo"===u?(e.resetPerformanceData(),e.showWelcomeMessage(),d("monitorando")):"monitorando"===u?d("relatorio"):"relatorio"!==u&&"relatorio_gerado"!==u||(e.showPerformanceSummary(!1),d("relatorio_gerado"))},c.onclick=function(){e.resetPerformanceData(),d("inativo")},this.showWelcomeMessage(),i.appendChild(s),i.appendChild(l),i.appendChild(p),i.appendChild(c),document.body.appendChild(i),document.body.appendChild(f),l.onclick=function(){e.showHttpRequestsReport()},p.onclick=function(){e.generateDetailedAnalysis()}}},e}();function f(e){return void 0===e&&(e="Service"),new p(e)}var m,u=f("GLOBAL"),d=(m=u,function(e){return function(o,t,r){var n,i,a,l=r.value;return"object"==typeof e&&null!==e?(n=e.name||t,i=e.method,a={ok:e.ok,lento:e.lento,critico:e.critico}):"function"==typeof e?(n=e.name||t,i=e):n="string"==typeof e?e:t,r.value=function(){for(var e=[],o=0;o<arguments.length;o++)e[o]=arguments[o];return s(this,void 0,void 0,(function(){var o,t;return c(this,(function(r){switch(r.label){case 0:if(o=this.performanceLogger,!(t=o||m))return[3,5];t.startTimer(n),r.label=1;case 1:return r.trys.push([1,,3,4]),[4,(i||l).apply(this,e)];case 2:return[2,r.sent()];case 3:return t.endTimer(n,void 0,a),[7];case 4:return[3,7];case 5:return[4,(i||l).apply(this,e)];case 6:return[2,r.sent()];case 7:return[2]}}))}))},r}});var h=function(){function e(){}return e.prototype.intercept=function(e,o){var n;if(!e.url.startsWith("./assets")){var i=sessionStorage.getItem("idTela");i||(i="SEL041",sessionStorage.setItem("idTela",i));var a=null!==(n=sessionStorage.getItem("cdUsuario"))&&void 0!==n?n:"",s=e.clone({headers:e.headers.set("tela_id",i).set("tela","SEL041").set("user",a)}),c=performance.now();return o.handle(s).pipe(r.tap({next:function(e){var o,r;if(e instanceof t.HttpResponse){var n=performance.now()-c,i=(null===(o=s.body)||void 0===o?void 0:o.operationType)||"UNKNOWN",a=(null===(r=s.body)||void 0===r?void 0:r.name)||"";console.log("%c🟢 [HTTP] "+i+" "+("SELECT_FULL"===i?"":a)+" - "+n.toFixed(1)+"ms","color: #6cbbd8ff; font-weight: bold;"),u.registerHttpRequest(s,n,!1)}},error:function(e){var o,t,r=performance.now()-c,n=(null===(o=s.body)||void 0===o?void 0:o.operationType)||"UNKNOWN",i=(null===(t=s.body)||void 0===t?void 0:t.name)||"";console.groupCollapsed("%c🔴 [HTTP] "+n+" "+i+" - "+r.toFixed(1)+"ms","color: #6cbbd8ff; font-weight: bold;"),console.error(e),console.groupEnd(),u.registerHttpRequest(s,r,!0)}}))}return o.handle(e)},e}();h.decorators=[{type:o.Injectable}],e.GlobalPerformanceLogger=u,e.PerformanceMonitor=d,e.PerformanceMonitorComponent=n,e.PerformanceMonitorInterceptor=h,e.PerformanceMonitorModule=i,e.PerformanceMonitorService=a,e.ɵa=p,e.ɵb=f,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=performance-monitor-logger.umd.min.js.map