pms_md 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,300 +1,321 @@
1
- /**
2
- * Node Monitor - Main Entry Point
3
- * Comprehensive monitoring solution for Node.js applications
4
- */
5
-
6
- const MonitoringConfig = require('./config/monitoringConfig');
7
- const ErrorLogger = require('./logger/errorLogger');
8
- const NotificationManager = require('./notifiers/notificationManager');
9
- const ApiErrorMonitor = require('./monitors/apiErrorMonitor');
10
- const ServerHealthMonitor = require('./monitors/serverHealthMonitor');
11
- const SystemResourceMonitor = require('./monitors/systemResourceMonitor');
12
- const DbConnectionMonitor = require('./monitors/dbConnectionMonitor');
13
-
14
- class NodeMonitor {
15
- constructor(userConfig = {}) {
16
- // Initialize configuration
17
- this.config = new MonitoringConfig(userConfig);
18
-
19
- // Initialize logger
20
- this.logger = new ErrorLogger(this.config.getAll());
21
-
22
- // Initialize notification manager
23
- this.notificationManager = new NotificationManager(this.config.getAll(), this.logger);
24
-
25
- // Initialize monitors
26
- this.apiErrorMonitor = new ApiErrorMonitor(
27
- this.config.getAll(),
28
- this.logger,
29
- this.notificationManager
30
- );
31
-
32
- this.serverHealthMonitor = new ServerHealthMonitor(
33
- this.config.getAll(),
34
- this.logger,
35
- this.notificationManager
36
- );
37
-
38
- this.systemResourceMonitor = new SystemResourceMonitor(
39
- this.config.getAll(),
40
- this.logger,
41
- this.notificationManager
42
- );
43
-
44
- this.dbConnectionMonitor = new DbConnectionMonitor(
45
- this.config.getAll(),
46
- this.logger,
47
- this.notificationManager
48
- );
49
-
50
- this.isStarted = false;
51
-
52
- this.logger.logInfo('Node Monitor initialized', {
53
- app: this.config.get('app.name'),
54
- version: this.config.get('app.version'),
55
- environment: this.config.get('app.environment')
56
- });
57
- }
58
-
59
- /**
60
- * Start all monitoring services
61
- */
62
- start() {
63
- if (this.isStarted) {
64
- this.logger.logWarning('monitor_already_started', 'Monitor is already started');
65
- return;
66
- }
67
-
68
- this.serverHealthMonitor.start();
69
- this.systemResourceMonitor.start();
70
- this.dbConnectionMonitor.start();
71
-
72
- this.isStarted = true;
73
- this.logger.logInfo('All monitoring services started');
74
- }
75
-
76
- /**
77
- * Stop all monitoring services
78
- */
79
- stop() {
80
- if (!this.isStarted) {
81
- return;
82
- }
83
-
84
- this.serverHealthMonitor.stop();
85
- this.systemResourceMonitor.stop();
86
- this.dbConnectionMonitor.stop();
87
-
88
- this.isStarted = false;
89
- this.logger.logInfo('All monitoring services stopped');
90
- }
91
-
92
- /**
93
- * Get Express error handling middleware
94
- */
95
- errorMiddleware() {
96
- return this.apiErrorMonitor.middleware();
97
- }
98
-
99
- /**
100
- * Get Express request logger middleware
101
- */
102
- requestLogger() {
103
- return this.apiErrorMonitor.requestLogger();
104
- }
105
-
106
- /**
107
- * Get 404 handler middleware
108
- */
109
- notFoundHandler() {
110
- return this.apiErrorMonitor.notFoundHandler();
111
- }
112
-
113
- /**
114
- * Get async error handler wrapper
115
- */
116
- asyncHandler(fn) {
117
- return this.apiErrorMonitor.asyncHandler(fn);
118
- }
119
-
120
- /**
121
- * Get health check endpoint handler
122
- */
123
- healthCheckEndpoint() {
124
- return this.serverHealthMonitor.healthCheckEndpoint();
125
- }
126
-
127
- /**
128
- * Get basic health info endpoint handler
129
- */
130
- healthInfoEndpoint() {
131
- return this.serverHealthMonitor.healthInfoEndpoint();
132
- }
133
-
134
- /**
135
- * Register a custom health check
136
- */
137
- registerHealthCheck(name, checkFunction) {
138
- this.serverHealthMonitor.registerHealthCheck(name, checkFunction);
139
- }
140
-
141
- /**
142
- * Register a database connection for monitoring
143
- */
144
- registerDatabase(name, type, connection, testQuery = null) {
145
- this.dbConnectionMonitor.registerConnection(name, type, connection, testQuery);
146
- }
147
-
148
- /**
149
- * Setup graceful shutdown handlers
150
- */
151
- setupGracefulShutdown(server) {
152
- this.serverHealthMonitor.setupGracefulShutdown(server);
153
- }
154
-
155
- /**
156
- * Get current monitoring status
157
- */
158
- getStatus() {
159
- return {
160
- isRunning: this.isStarted,
161
- health: this.serverHealthMonitor.getStatus(),
162
- system: this.systemResourceMonitor.getCurrentMetrics(),
163
- databases: this.dbConnectionMonitor.getStatus(),
164
- errors: this.apiErrorMonitor.getStats()
165
- };
166
- }
167
-
168
- /**
169
- * Get system information
170
- */
171
- getSystemInfo() {
172
- return this.systemResourceMonitor.getSystemInfo();
173
- }
174
-
175
- /**
176
- * Get metrics history
177
- */
178
- getMetricsHistory() {
179
- return this.systemResourceMonitor.getMetricsHistory();
180
- }
181
-
182
- /**
183
- * Get database statistics
184
- */
185
- async getDatabaseStats(name) {
186
- return this.dbConnectionMonitor.getStats(name);
187
- }
188
-
189
- /**
190
- * Send custom notification
191
- */
192
- async notify(level, subject, message, details = {}) {
193
- switch (level.toLowerCase()) {
194
- case 'critical':
195
- return this.notificationManager.sendCritical(subject, message, details);
196
- case 'warning':
197
- return this.notificationManager.sendWarning(subject, message, details);
198
- case 'info':
199
- return this.notificationManager.sendInfo(subject, message, details);
200
- case 'recovery':
201
- return this.notificationManager.sendRecovery(subject, message, details);
202
- default:
203
- return this.notificationManager.sendInfo(subject, message, details);
204
- }
205
- }
206
-
207
- /**
208
- * Log custom error
209
- */
210
- logError(type, message, details = {}) {
211
- return this.logger.logSystemError(type, message, details);
212
- }
213
-
214
- /**
215
- * Log custom warning
216
- */
217
- logWarning(type, message, details = {}) {
218
- return this.logger.logWarning(type, message, details);
219
- }
220
-
221
- /**
222
- * Log custom info
223
- */
224
- logInfo(message, details = {}) {
225
- return this.logger.logInfo(message, details);
226
- }
227
-
228
- /**
229
- * Get Winston logger instance for custom logging
230
- */
231
- getLogger() {
232
- return this.logger.getLogger();
233
- }
234
-
235
- /**
236
- * Get configuration
237
- */
238
- getConfig() {
239
- return this.config.getSanitized();
240
- }
241
-
242
- /**
243
- * Update configuration at runtime
244
- */
245
- updateConfig(path, value) {
246
- this.config.set(path, value);
247
- this.logger.logInfo('Configuration updated', { path, value });
248
- }
249
-
250
- /**
251
- * Create a monitoring dashboard endpoint (returns JSON data)
252
- */
253
- dashboardEndpoint() {
254
- return async (req, res) => {
255
- try {
256
- const status = this.getStatus();
257
- const systemInfo = this.getSystemInfo();
258
- const metricsHistory = this.getMetricsHistory();
259
-
260
- res.json({
261
- status: 'ok',
262
- timestamp: new Date().toISOString(),
263
- application: {
264
- name: this.config.get('app.name'),
265
- version: this.config.get('app.version'),
266
- environment: this.config.get('app.environment')
267
- },
268
- monitoring: status,
269
- system: systemInfo,
270
- metrics: metricsHistory
271
- });
272
- } catch (error) {
273
- res.status(500).json({
274
- status: 'error',
275
- error: error.message
276
- });
277
- }
278
- };
279
- }
280
-
281
- /**
282
- * Static method to create error with status code
283
- */
284
- static createError(message, statusCode = 500, details = {}) {
285
- return ApiErrorMonitor.createError(message, statusCode, details);
286
- }
287
- }
288
-
289
- // Export the main class
290
- module.exports = NodeMonitor;
291
-
292
- // Also export individual components for advanced usage
293
- module.exports.MonitoringConfig = MonitoringConfig;
294
- module.exports.ErrorLogger = ErrorLogger;
295
- module.exports.NotificationManager = NotificationManager;
296
- module.exports.ApiErrorMonitor = ApiErrorMonitor;
297
- module.exports.ServerHealthMonitor = ServerHealthMonitor;
298
- module.exports.SystemResourceMonitor = SystemResourceMonitor;
299
- module.exports.DbConnectionMonitor = DbConnectionMonitor;
300
-
1
+ /**
2
+ * Node Monitor - Main Entry Point
3
+ * Comprehensive monitoring solution for Node.js applications
4
+ */
5
+
6
+ const MonitoringConfig = require('./config/monitoringConfig');
7
+ const ErrorLogger = require('./logger/errorLogger');
8
+ const NotificationManager = require('./notifiers/notificationManager');
9
+ const ApiErrorMonitor = require('./monitors/apiErrorMonitor');
10
+ const ServerHealthMonitor = require('./monitors/serverHealthMonitor');
11
+ const SystemResourceMonitor = require('./monitors/systemResourceMonitor');
12
+ const DbConnectionMonitor = require('./monitors/dbConnectionMonitor');
13
+
14
+ class NodeMonitor {
15
+ constructor(userConfig = {}) {
16
+ // Initialize configuration
17
+ this.config = new MonitoringConfig(userConfig);
18
+
19
+ // Initialize logger
20
+ this.logger = new ErrorLogger(this.config.getAll());
21
+
22
+ // Initialize notification manager
23
+ this.notificationManager = new NotificationManager(this.config.getAll(), this.logger);
24
+
25
+ // Initialize monitors
26
+ this.apiErrorMonitor = new ApiErrorMonitor(
27
+ this.config.getAll(),
28
+ this.logger,
29
+ this.notificationManager
30
+ );
31
+
32
+ this.serverHealthMonitor = new ServerHealthMonitor(
33
+ this.config.getAll(),
34
+ this.logger,
35
+ this.notificationManager
36
+ );
37
+
38
+ this.systemResourceMonitor = new SystemResourceMonitor(
39
+ this.config.getAll(),
40
+ this.logger,
41
+ this.notificationManager
42
+ );
43
+
44
+ this.dbConnectionMonitor = new DbConnectionMonitor(
45
+ this.config.getAll(),
46
+ this.logger,
47
+ this.notificationManager
48
+ );
49
+
50
+ this.isStarted = false;
51
+
52
+ this.logger.logInfo('Node Monitor initialized', {
53
+ app: this.config.get('app.name'),
54
+ version: this.config.get('app.version'),
55
+ environment: this.config.get('app.environment')
56
+ });
57
+ }
58
+
59
+ /**
60
+ * Start all monitoring services
61
+ */
62
+ start() {
63
+ if (this.isStarted) {
64
+ this.logger.logWarning('monitor_already_started', 'Monitor is already started');
65
+ return;
66
+ }
67
+
68
+ this.serverHealthMonitor.start();
69
+ this.systemResourceMonitor.start();
70
+ this.dbConnectionMonitor.start();
71
+
72
+ this.isStarted = true;
73
+ this.logger.logInfo('All monitoring services started');
74
+ }
75
+
76
+ /**
77
+ * Stop all monitoring services
78
+ */
79
+ stop() {
80
+ if (!this.isStarted) {
81
+ return;
82
+ }
83
+
84
+ this.serverHealthMonitor.stop();
85
+ this.systemResourceMonitor.stop();
86
+ this.dbConnectionMonitor.stop();
87
+
88
+ this.isStarted = false;
89
+ this.logger.logInfo('All monitoring services stopped');
90
+ }
91
+
92
+ /**
93
+ * Get Express error handling middleware
94
+ */
95
+ errorMiddleware() {
96
+ return this.apiErrorMonitor.middleware();
97
+ }
98
+
99
+ /**
100
+ * Get Express request logger middleware
101
+ */
102
+ requestLogger() {
103
+ return this.apiErrorMonitor.requestLogger();
104
+ }
105
+
106
+ /**
107
+ * Get 404 handler middleware
108
+ */
109
+ notFoundHandler() {
110
+ return this.apiErrorMonitor.notFoundHandler();
111
+ }
112
+
113
+ /**
114
+ * Get async error handler wrapper
115
+ */
116
+ asyncHandler(fn) {
117
+ return this.apiErrorMonitor.asyncHandler(fn);
118
+ }
119
+
120
+ /**
121
+ * Get health check endpoint handler
122
+ */
123
+ healthCheckEndpoint() {
124
+ return this.serverHealthMonitor.healthCheckEndpoint();
125
+ }
126
+
127
+ /**
128
+ * Get basic health info endpoint handler
129
+ */
130
+ healthInfoEndpoint() {
131
+ return this.serverHealthMonitor.healthInfoEndpoint();
132
+ }
133
+
134
+ /**
135
+ * Register a custom health check
136
+ */
137
+ registerHealthCheck(name, checkFunction) {
138
+ this.serverHealthMonitor.registerHealthCheck(name, checkFunction);
139
+ }
140
+
141
+ /**
142
+ * Register a database connection for monitoring
143
+ */
144
+ registerDatabase(name, type, connection, testQuery = null) {
145
+ this.dbConnectionMonitor.registerConnection(name, type, connection, testQuery);
146
+ }
147
+
148
+ /**
149
+ * Setup graceful shutdown handlers
150
+ */
151
+ setupGracefulShutdown(server) {
152
+ this.serverHealthMonitor.setupGracefulShutdown(server);
153
+ }
154
+
155
+ /**
156
+ * Get current monitoring status
157
+ */
158
+ getStatus() {
159
+ return {
160
+ isRunning: this.isStarted,
161
+ health: this.serverHealthMonitor.getStatus(),
162
+ system: this.systemResourceMonitor.getCurrentMetrics(),
163
+ databases: this.dbConnectionMonitor.getStatus(),
164
+ errors: this.apiErrorMonitor.getStats()
165
+ };
166
+ }
167
+
168
+ /**
169
+ * Get system information
170
+ */
171
+ getSystemInfo() {
172
+ return this.systemResourceMonitor.getSystemInfo();
173
+ }
174
+
175
+ /**
176
+ * Get metrics history
177
+ */
178
+ getMetricsHistory() {
179
+ return this.systemResourceMonitor.getMetricsHistory();
180
+ }
181
+
182
+ /**
183
+ * Get database statistics
184
+ */
185
+ async getDatabaseStats(name) {
186
+ return this.dbConnectionMonitor.getStats(name);
187
+ }
188
+
189
+ /**
190
+ * Send custom notification
191
+ */
192
+ async notify(level, subject, message, details = {}) {
193
+ switch (level.toLowerCase()) {
194
+ case 'critical':
195
+ return this.notificationManager.sendCritical(subject, message, details);
196
+ case 'warning':
197
+ return this.notificationManager.sendWarning(subject, message, details);
198
+ case 'info':
199
+ return this.notificationManager.sendInfo(subject, message, details);
200
+ case 'recovery':
201
+ return this.notificationManager.sendRecovery(subject, message, details);
202
+ default:
203
+ return this.notificationManager.sendInfo(subject, message, details);
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Log custom error
209
+ */
210
+ logError(type, message, details = {}) {
211
+ return this.logger.logSystemError(type, message, details);
212
+ }
213
+
214
+ /**
215
+ * Log custom warning
216
+ */
217
+ logWarning(type, message, details = {}) {
218
+ return this.logger.logWarning(type, message, details);
219
+ }
220
+
221
+ /**
222
+ * Log custom info
223
+ */
224
+ logInfo(message, details = {}) {
225
+ return this.logger.logInfo(message, details);
226
+ }
227
+
228
+ /**
229
+ * Get Winston logger instance for custom logging
230
+ */
231
+ getLogger() {
232
+ return this.logger.getLogger();
233
+ }
234
+
235
+ /**
236
+ * Get configuration
237
+ */
238
+ getConfig() {
239
+ return this.config.getSanitized();
240
+ }
241
+
242
+ /**
243
+ * Update configuration at runtime
244
+ */
245
+ updateConfig(path, value) {
246
+ this.config.set(path, value);
247
+ this.logger.logInfo('Configuration updated', { path, value });
248
+ }
249
+
250
+ /**
251
+ * Serve monitoring UI (HTML dashboards)
252
+ * Automatically sets up EJS views and static files from the package
253
+ *
254
+ * @param {Express.Application} app - Express application instance
255
+ * @param {Object} options - UI configuration options
256
+ * @param {string} options.basePath - Base path for UI routes (default: '')
257
+ * @param {boolean} options.enableErrorLogs - Enable error logs page (default: true)
258
+ * @param {string} options.appName - Application name for UI (default: from config)
259
+ * @returns {UIRouter} UI Router instance
260
+ *
261
+ * @example
262
+ * const monitor = new NodeMonitor({ app: { name: 'My App' } });
263
+ * monitor.serveUI(app);
264
+ * // UI available at: /, /health, /monitor/dashboard, /monitor/metrics
265
+ */
266
+ serveUI(app, options = {}) {
267
+ const uiRouter = require('./ui/uiRouter');
268
+ return uiRouter.setup(app, this, options);
269
+ }
270
+
271
+ /**
272
+ * Create a monitoring dashboard endpoint (returns JSON data)
273
+ */
274
+ dashboardEndpoint() {
275
+ return async (req, res) => {
276
+ try {
277
+ const status = this.getStatus();
278
+ const systemInfo = this.getSystemInfo();
279
+ const metricsHistory = this.getMetricsHistory();
280
+
281
+ res.json({
282
+ status: 'ok',
283
+ timestamp: new Date().toISOString(),
284
+ application: {
285
+ name: this.config.get('app.name'),
286
+ version: this.config.get('app.version'),
287
+ environment: this.config.get('app.environment')
288
+ },
289
+ monitoring: status,
290
+ system: systemInfo,
291
+ metrics: metricsHistory
292
+ });
293
+ } catch (error) {
294
+ res.status(500).json({
295
+ status: 'error',
296
+ error: error.message
297
+ });
298
+ }
299
+ };
300
+ }
301
+
302
+ /**
303
+ * Static method to create error with status code
304
+ */
305
+ static createError(message, statusCode = 500, details = {}) {
306
+ return ApiErrorMonitor.createError(message, statusCode, details);
307
+ }
308
+ }
309
+
310
+ // Export the main class
311
+ module.exports = NodeMonitor;
312
+
313
+ // Also export individual components for advanced usage
314
+ module.exports.MonitoringConfig = MonitoringConfig;
315
+ module.exports.ErrorLogger = ErrorLogger;
316
+ module.exports.NotificationManager = NotificationManager;
317
+ module.exports.ApiErrorMonitor = ApiErrorMonitor;
318
+ module.exports.ServerHealthMonitor = ServerHealthMonitor;
319
+ module.exports.SystemResourceMonitor = SystemResourceMonitor;
320
+ module.exports.DbConnectionMonitor = DbConnectionMonitor;
321
+