UNPKG

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.

78 lines 2.83 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LokiLogRepository = void 0; class LokiLogRepository { constructor(config, httpClient, formatter, circuitBreaker) { this.config = config; this.httpClient = httpClient; this.formatter = formatter; this.circuitBreaker = circuitBreaker; this.buffer = []; this.errorCount = 0; } async save(entry) { this.buffer.push(entry); // Auto-flush if buffer is full if (this.buffer.length >= 100) { await this.flush(); } } async saveBatch(entries) { this.buffer.push(...entries); await this.flush(); } async flush() { var _a, _b, _c, _d, _e; if (this.buffer.length === 0) { return; } // Check circuit breaker if (this.circuitBreaker.isOpen()) { return; } const entries = this.buffer.splice(0); try { const payload = this.formatter.format(entries); await this.httpClient.post(this.config.url, payload, { headers: this.buildHeaders(), timeout: (_a = this.config.timeout) !== null && _a !== void 0 ? _a : 5000, retries: (_b = this.config.maxRetries) !== null && _b !== void 0 ? _b : 3, retryDelay: (_c = this.config.retryDelay) !== null && _c !== void 0 ? _c : 1000, compression: (_d = this.config.compression) !== null && _d !== void 0 ? _d : true, compressionLevel: (_e = this.config.compressionLevel) !== null && _e !== void 0 ? _e : 6, }); this.circuitBreaker.recordSuccess(); this.lastSuccessfulFlush = Date.now(); this.errorCount = 0; } catch (error) { this.circuitBreaker.recordFailure(); this.errorCount++; // Re-add entries to buffer on failure (with limit) if (this.buffer.length < 1000) { this.buffer.unshift(...entries.slice(0, 500)); } throw error; } } async getHealth() { return { healthy: this.errorCount < 10 && !this.circuitBreaker.isOpen(), lastSuccessfulFlush: this.lastSuccessfulFlush, errorCount: this.errorCount, pendingEntries: this.buffer.length, }; } buildHeaders() { const headers = { 'Content-Type': 'application/json', 'X-Scope-OrgID': this.config.tenantId, }; if (this.config.authToken) { headers['Authorization'] = `Bearer ${this.config.authToken}`; } return headers; } } exports.LokiLogRepository = LokiLogRepository; //# sourceMappingURL=LokiLogRepository.js.map