-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloggingMiddleware.js
More file actions
44 lines (34 loc) · 1.67 KB
/
loggingMiddleware.js
File metadata and controls
44 lines (34 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const pool = require('./db');
const loggingMiddleware = (req, res, next) => {
// Use the 'finish' event to log after the response is sent
res.on('finish', async () => {
const { method, originalUrl } = req;
const status = res.statusCode;
// Don't log frequent polling of sensor values
if (originalUrl === '/sensor-values') {
return;
}
// Ensure body is not undefined for requests without a body (e.g., GET)
const body = req.body || {};
// Determine sensor_or_relay_id from body or query parameters
const sensorOrRelayId = body.relayName || req.query.id || null;
// Sanitize payload to avoid storing sensitive info if needed in future
const payload = body;
// Log to console with the final status code
console.log(`[AUDIT LOG] Method: ${method}, Endpoint: ${originalUrl}, Status: ${status}, Payload: ${JSON.stringify(payload)}`);
try {
// Log to the database
const [result] = await pool.execute(
'INSERT INTO sensor_logs (endpoint, method, sensor_or_relay_id, payload, status) VALUES (?, ?, ?, ?, ?)',
[originalUrl, method, sensorOrRelayId, JSON.stringify(payload), status]
);
console.log(`[DB LOG] Inserted log with ID: ${result.insertId}`);
} catch (error) {
// If the database insert fails, log the error but don't crash the server
console.error('[DB LOG ERROR] Failed to insert audit log into database:', error);
}
});
// Proceed to the next middleware or route handler
next();
};
module.exports = loggingMiddleware;