@merncloud/nodejs-monitoring
Version:
A comprehensive monitoring service for Node.js applications with built-in health probes and metrics collection
59 lines • 1.91 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestTracker = void 0;
class RequestTracker {
constructor() {
this.totalRequests = 0;
this.activeRequests = 0;
this.totalResponseTime = 0;
this.errors = 0;
this.requestTimes = [];
this.errorTimes = [];
}
static getInstance() {
if (!RequestTracker.instance) {
RequestTracker.instance = new RequestTracker();
}
return RequestTracker.instance;
}
startRequest() {
this.totalRequests++;
this.activeRequests++;
return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
endRequest(requestId, startTime) {
this.activeRequests--;
const responseTime = Date.now() - startTime;
this.totalResponseTime += responseTime;
this.requestTimes.push(responseTime);
if (this.requestTimes.length > 100) {
this.requestTimes.shift();
}
}
recordError() {
this.errors++;
this.errorTimes.push(Date.now());
if (this.errorTimes.length > 100) {
this.errorTimes.shift();
}
}
getMetrics() {
const now = Date.now();
const fiveMinutesAgo = now - 5 * 60 * 1000;
const recentErrors = this.errorTimes.filter((time) => time > fiveMinutesAgo);
return {
total: this.totalRequests,
active: this.activeRequests,
averageResponseTime: this.requestTimes.length > 0
? Math.round(this.requestTimes.reduce((a, b) => a + b, 0) /
this.requestTimes.length)
: 0,
errors: {
total: this.errors,
rate: recentErrors.length / 5,
},
};
}
}
exports.RequestTracker = RequestTracker;
//# sourceMappingURL=RequestTracker.js.map