feat: improve logging

This commit is contained in:
Rim
2025-04-01 16:29:29 -04:00
parent e16a0a85ee
commit 0df8728515
2 changed files with 276 additions and 30 deletions

48
app.js
View File

@ -899,6 +899,8 @@ app.post("/api/search", async (req, res) => {
app.post('/api/log', (req, res) => {
const clientIP = req.headers['x-forwarded-for'] || req.ip || req.connection.remoteAddress;
const userAgent = req.headers['user-agent'];
const referer = req.headers['referer'];
const origin = req.headers['origin'];
let logData;
try {
@ -912,11 +914,25 @@ app.post('/api/log', (req, res) => {
logData = { eventType: 'unknown', timestamp: new Date().toISOString() };
}
// Log the data
console.log(`[USER ACTIVITY] ${new Date().toISOString()} | IP: ${clientIP} | Type: ${logData.eventType} | ${JSON.stringify({
// Enrich log with server-side data
const enrichedLog = {
...logData,
userAgent
})}`);
meta: {
clientIP,
userAgent,
referer,
origin,
requestHeaders: sanitizeHeaders(req.headers),
serverTimestamp: new Date().toISOString(),
requestId: req.id || Math.random().toString(36).substring(2, 15)
}
};
// For structured logging in production, consider using a logging service
console.log(`[USER_ACTIVITY] ${JSON.stringify(enrichedLog)}`);
// Optional: Store logs in database for advanced analytics
// storeLogInDatabase(enrichedLog);
} catch (error) {
console.error('Error processing log data:', error);
@ -927,6 +943,30 @@ app.post('/api/log', (req, res) => {
res.status(200).send();
});
// Helper function to remove sensitive data from headers
function sanitizeHeaders(headers) {
const safeHeaders = { ...headers };
// Remove potential sensitive information
const sensitiveHeaders = ['authorization', 'cookie', 'set-cookie'];
sensitiveHeaders.forEach(header => {
if (safeHeaders[header]) {
safeHeaders[header] = '[REDACTED]';
}
});
return safeHeaders;
}
// Database storage function
/*
function storeLogInDatabase(logData) {
// Example with MongoDB
db.collection('user_logs').insertOne(logData)
.catch(err => console.error('Failed to store log in database:', err));
}
*/
// Basic health check endpoint
app.get("/health", (req, res) => {
res.json({ status: "ok", timestamp: new Date().toISOString() });