feat: improve logging
This commit is contained in:
48
app.js
48
app.js
@ -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() });
|
||||
|
Reference in New Issue
Block a user