logs-interceptor
Version:
High-performance, production-ready log interceptor for Node.js applications with Loki integration. Built with Clean Architecture principles. Supports Node.js, Browser, and Node-RED.
101 lines • 3.19 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MemoryBuffer = void 0;
class MemoryBuffer {
constructor(config) {
this.config = config;
this.entries = [];
this.lastFlushTime = Date.now();
this.flushTimer = null;
if (config.autoFlush) {
this.scheduleFlush();
}
}
add(entry) {
// Remove old entries if buffer is full
if (this.entries.length >= this.config.maxSize) {
this.removeOldEntries();
}
this.entries.push(entry);
// Auto-flush if buffer is full
if (this.entries.length >= this.config.maxSize && this.config.autoFlush) {
this.scheduleFlush();
}
}
flush() {
if (this.flushTimer) {
clearTimeout(this.flushTimer);
this.flushTimer = null;
}
const entries = [...this.entries];
this.entries = [];
this.lastFlushTime = Date.now();
if (this.config.autoFlush) {
this.scheduleFlush();
}
return entries;
}
peek() {
return [...this.entries];
}
size() {
return this.entries.length;
}
isFull() {
return this.entries.length >= this.config.maxSize;
}
shouldFlush() {
const timeSinceLastFlush = Date.now() - this.lastFlushTime;
return (this.entries.length >= this.config.maxSize ||
(this.config.autoFlush &&
timeSinceLastFlush >= this.config.flushInterval));
}
clear() {
this.entries = [];
if (this.flushTimer) {
clearTimeout(this.flushTimer);
this.flushTimer = null;
}
}
getMetrics() {
const oldestEntry = this.entries[0]
? Date.parse(this.entries[0].timestamp)
: undefined;
const newestEntry = this.entries[this.entries.length - 1]
? Date.parse(this.entries[this.entries.length - 1].timestamp)
: undefined;
// Estimate memory usage
const memoryUsageMB = JSON.stringify(this.entries).length / 1024 / 1024;
return {
size: this.entries.length,
maxSize: this.config.maxSize,
oldestEntry,
newestEntry,
memoryUsageMB,
};
}
removeOldEntries() {
const now = Date.now();
const maxAge = this.config.maxAge;
this.entries = this.entries.filter((entry) => {
const entryAge = now - Date.parse(entry.timestamp);
return entryAge < maxAge;
});
// If still full, remove oldest entries
if (this.entries.length >= this.config.maxSize) {
const removeCount = Math.floor(this.config.maxSize * 0.1);
this.entries = this.entries.slice(removeCount);
}
}
scheduleFlush() {
if (this.flushTimer) {
return;
}
this.flushTimer = setTimeout(() => {
this.flushTimer = null;
// Flush will be called by the service
}, this.config.flushInterval);
}
}
exports.MemoryBuffer = MemoryBuffer;
//# sourceMappingURL=MemoryBuffer.js.map