import fs from 'fs'; import moment from "moment"; const shortenStringsInObject = (obj, maxLength) => { // Kiểm tra nếu obj không phải là một đối tượng hoặc maxLength không phải là một số if (typeof obj !== 'object' || typeof maxLength !== 'number') { return obj; } // Duyệt qua các thuộc tính của đối tượng for (const key in obj) { if (obj.hasOwnProperty(key)) { // Kiểm tra nếu thuộc tính là một chuỗi và độ dài của chuỗi lớn hơn maxLength if (typeof obj[key] === 'string' && obj[key].length > maxLength) { // Rút ngắn chuỗi lại maxLength ký tự obj[key] = obj[key].substring(0, maxLength); } if (Array.isArray(obj[key]) && obj[key].length > 20) { // Rút ngắn chuỗi lại maxLength ký tự obj[key] = obj[key].slice(0,20) } } } return obj; } export function loggerAPI(request, response, location) { let old_data = ""; let body = shortenStringsInObject(response.getBody(), 300) try { const fileName = "./app/store/logsAPI/" + moment(Date.now()).format("DD_MM_YYYY").toString() + ".log"; let logInfo = "\n\n[" + moment(Date.now()).format("D/M/YY-HH:mm:ss") + "] - " + response.getStatus() + " - " + location + "\n------------PAYLOAD-----------\n" + JSON.stringify(request.all()) + "\n--------------DATA-------------\n" + JSON.stringify(body) + "\n-------------------------------"; fs.exists(fileName, async (exists) => { if (exists) { old_data = await fs.readFileSync(fileName, "utf8"); fs.writeFileSync(fileName, old_data + logInfo); } else { fs.writeFileSync(fileName, old_data + logInfo); } }); } catch (error) { response.status(500).send("CAN'T WRITE LOG"); } }