prod124njac/prod124njac-back-b/authsec_node/Backend/middleware/userLogger.js

32 lines
925 B
JavaScript
Raw Permalink Normal View History

2024-09-18 04:14:45 +00:00
const fs = require("fs")
const path = require("path")
function userLogger(req, res, next) {
const { user_id, user_name, email } = req.user
// Create a directory for the user if it doesn't exist
const userDir = path.join(__dirname, "../logs", user_name)
if (!fs.existsSync(userDir)) {
fs.mkdirSync(userDir, { recursive: true })
}
// Create a log file with the current date
const currentDate = new Date().toISOString().slice(0, 10) // Get YYYY-MM-DD format
const logFile = path.join(userDir, `${currentDate}.log`)
// Log data to the console
console.log(`[${user_name}] Request to ${req.originalUrl}`)
// Log data to the user-specific log file
const logMessage = `[${new Date()}] ${req.method} ${req.originalUrl}\n`
fs.appendFile(logFile, logMessage, (err) => {
if (err) {
console.error(`Failed to log data to ${logFile}: ${err}`)
}
})
next()
}
module.exports = userLogger