UNPKG

@hemantwasthere/monitoring-sdk

Version:

Centralized monitoring SDK for Node.js applications with Prometheus, Loki, and Grafana integration

91 lines (90 loc) 3.39 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronMonitor = void 0; const index_1 = require("./index"); const logging_1 = require("./logging"); const metrics_1 = require("./metrics"); class CronMonitor { getMetricsService() { if (!this.metricsService) { try { const currentSDK = index_1.MonitoringSDK.getInstance(); const currentConfig = currentSDK.getConfig(); this.metricsService = metrics_1.MetricsService.getInstance(currentConfig); } catch { // Fallback if no SDK instance exists this.metricsService = metrics_1.MetricsService.getInstance(); } } return this.metricsService; } getLoggingService() { if (!this.loggingService) { try { const currentSDK = index_1.MonitoringSDK.getInstance(); const currentConfig = currentSDK.getConfig(); this.loggingService = logging_1.LoggingService.getInstance(currentConfig); } catch { this.loggingService = logging_1.LoggingService.getInstance(); } } return this.loggingService; } // Decorator to monitor cron job execution static monitor(jobName) { return function (target, propertyKey, descriptor) { const originalMethod = descriptor.value; const cronMonitor = new CronMonitor(); descriptor.value = async function (...args) { const startTime = Date.now(); let success = true; let error; try { cronMonitor.getLoggingService().info(`Starting cron job: ${jobName}`); const result = await originalMethod.apply(this, args); cronMonitor .getLoggingService() .info(`Completed cron job: ${jobName}`); return result; } catch (err) { success = false; error = err instanceof Error ? err.message : "Unknown error"; cronMonitor .getLoggingService() .error(`Cron job failed: ${jobName}`, err); throw err; } finally { const duration = Date.now() - startTime; const metric = { jobName, success, duration, error, }; cronMonitor.getMetricsService().recordCronJob(metric); } }; return descriptor; }; } // Manual method to record cron job metrics recordJob(metric) { this.getMetricsService().recordCronJob(metric); if (metric.success) { this.getLoggingService().info(`Cron job completed: ${metric.jobName}`, { duration: metric.duration, }); } else { this.getLoggingService().error(`Cron job failed: ${metric.jobName}`, { duration: metric.duration, error: metric.error, }); } } } exports.CronMonitor = CronMonitor;