Update folder get logs

This commit is contained in:
Joseph Le 2026-02-26 17:52:00 +11:00
parent fd6568ddd1
commit 3d41d03f79
4 changed files with 180 additions and 4 deletions

View File

@ -14,3 +14,5 @@
directory = /home/Log_service/ directory = /home/Log_service/
directory = /home/Log_service/ directory = /home/Log_service/
directory = /home/Log_service/ directory = /home/Log_service/
directory = /home/Log_service/
directory = /home/Log_service/

View File

@ -7,6 +7,7 @@ const path = require("path");
const BASE_URL = Env.get("BASE_URL_LOG"); const BASE_URL = Env.get("BASE_URL_LOG");
const BASE_URL_AUTO = `${BASE_URL}/`; const BASE_URL_AUTO = `${BASE_URL}/`;
const LOG_DIR = "home/logs";
export default class ErpsController { export default class ErpsController {
/** /**
* Controller do tim cac serial number trong cac log trong khoang thoi gian xac dinh * Controller do tim cac serial number trong cac log trong khoang thoi gian xac dinh
@ -18,7 +19,7 @@ export default class ErpsController {
response, response,
}: HttpContextContract) { }: HttpContextContract) {
const { from, to } = request.all(); const { from, to } = request.all();
const getListLog = async (from, to) => { const getListLogOld = async (from, to) => {
try { try {
const listLog: string[] = []; const listLog: string[] = [];
const response = await axios.get(BASE_URL); const response = await axios.get(BASE_URL);
@ -58,6 +59,44 @@ export default class ErpsController {
} }
}; };
const getListLog = async (from: string, to: string) => {
try {
const listLog: string[] = [];
// đọc danh sách file trong thư mục
const files = await fs.readdirSync(LOG_DIR);
// lọc file .log
const logFiles = files.filter((file) => file.endsWith(".log"));
// dùng Promise.all để xử lý async đúng cách
await Promise.all(
logFiles.map(async (fileName) => {
const prefixNumber = parseInt(fileName.split("-")[0]);
if (
prefixNumber >= parseInt(from) &&
prefixNumber <= parseInt(to)
) {
listLog.push(path.join(LOG_DIR, fileName));
const record = await LogDetectFile.firstOrCreate(
{ file_name: fileName },
{ file_name: fileName }
);
console.log(record.toJSON());
}
})
);
return listLog;
} catch (error) {
console.log(error);
return [];
}
};
const fetchWithRetry = async (url) => { const fetchWithRetry = async (url) => {
let retries = 0; let retries = 0;
const MAX_RETRIES = 10; const MAX_RETRIES = 10;
@ -279,7 +318,7 @@ export default class ErpsController {
* @param {Integer} range khoang dong truoc/sau line * @param {Integer} range khoang dong truoc/sau line
* @author {Token} req.headers.authorization //token xac thuc * @author {Token} req.headers.authorization //token xac thuc
*/ */
public async getParagraph({ request, response }: HttpContextContract) { public async getParagraphOld({ request, response }: HttpContextContract) {
const { fileName, line, range } = request.all(); const { fileName, line, range } = request.all();
try { try {
@ -302,6 +341,34 @@ export default class ErpsController {
} }
} }
public async getParagraph({ request, response }: HttpContextContract) {
const { fileName, line, range } = request.all();
try {
let fName = fileName;
// const res = await axios.get(BASE_URL + "/" + fName);
const LOG_DIR = "/home/logs";
const filePath = path.join(LOG_DIR, fileName);
const res = await fs.readFileSync(filePath, "utf-8");
const arrayLine = res?.split("\n");
if (Number(range) >= Number(line)) {
response.status(200).json({
content: arrayLine?.slice(0, line + range)?.join("\n"),
});
} else {
response.status(200).json({
content: arrayLine?.slice(line - range - 1, line + range)?.join("\n"),
});
}
} catch (error) {
console.log(error);
response.status(202).send({ mess: "FILE NOT FOUND", error: error });
}
}
public async store({ request, response }: HttpContextContract) { } public async store({ request, response }: HttpContextContract) { }
public async show({ }: HttpContextContract) { } public async show({ }: HttpContextContract) { }

View File

@ -5,11 +5,13 @@ import LogDetectFile from "App/Models/LogDetectFile";
import axios from "axios"; import axios from "axios";
import Env from "@ioc:Adonis/Core/Env"; import Env from "@ioc:Adonis/Core/Env";
import { checkSpecialVersion } from "App/utils/helper"; import { checkSpecialVersion } from "App/utils/helper";
import path from "path";
import fs from "fs";
const BASE_URL = Env.get("BASE_URL_LOG"); const BASE_URL = Env.get("BASE_URL_LOG");
export default class LogsController { export default class LogsController {
public async showLog({ request, response }: HttpContextContract) { public async showLogOld({ request, response }: HttpContextContract) {
try { try {
const fileName = decodeURIComponent(request.params().name); const fileName = decodeURIComponent(request.params().name);
console.log(fileName); console.log(fileName);
@ -108,6 +110,111 @@ export default class LogsController {
} }
} }
public async showLog({ request, response }: HttpContextContract) {
try {
const fileName = decodeURIComponent(request.params().name);
console.log(fileName);
const fileDetect = await LogDetectFile.findBy("file_name", fileName);
if (!fileDetect) {
return response.status(203).send("FILE NOT FOUND");
}
const logsDetect = await Database.rawQuery(
"SELECT * FROM log_reports WHERE id_file = ?",
[fileDetect.id_ldf]
);
const lines = [...new Set(logsDetect[0].map((obj) => obj.line))].sort(
(a: number, b: number) => a - b
);
const logUrl = `${BASE_URL}/${fileName}`;
// const content = await axios.get(logUrl);
// Get log from home/logs
const LOG_DIR = "/home/logs";
const filePath = path.join(LOG_DIR, fileName);
const content = await fs.readFileSync(filePath, "utf-8");
const allKeyValues = await KeyValue.all();
const keyValueMap = allKeyValues.reduce((acc, { $original }) => {
acc[$original.key] = acc[$original.key] || [];
acc[$original.key].push($original.value);
return acc;
}, {} as Record<string, string[]>);
const MODEL_SPECIAL = keyValueMap["MODEL_SPECIAL"] || [];
const CATCH_FAULTY = keyValueMap["CATCH_FAULTY"] || [];
const EXCLUDE_ERR = keyValueMap["EXCLUDE_ERR"] || [];
const rawData = content.split("\n");
const processedData: string[] = [];
const modelSpecialDetected: string[] = [];
const issueSpecialDetected: string[] = [];
for (let i = 0; i < rawData.length; i++) {
let line = rawData[i];
let numberedLine = `${i + 1}|-|${line}`;
const specialVersion = checkSpecialVersion(line);
if (specialVersion) {
const index = numberedLine.indexOf(specialVersion);
numberedLine =
numberedLine.slice(0, index) +
"|-|" +
specialVersion +
"|-|" +
numberedLine.slice(index + specialVersion.length);
}
for (const value of [...MODEL_SPECIAL, ...CATCH_FAULTY]) {
if (
line.includes(value) &&
!EXCLUDE_ERR.some((err) => line.includes(err))
) {
const index = numberedLine.indexOf(value);
numberedLine =
numberedLine.slice(0, index) +
"|-|" +
value +
"|-|" +
numberedLine.slice(index + value.length);
break;
}
}
processedData.push(numberedLine);
}
for (const lineIndex of lines) {
const line = processedData[Number(lineIndex) - 1];
if (!line) continue;
if (EXCLUDE_ERR.some((err) => line.includes(err))) continue;
if (
MODEL_SPECIAL.some((model) => line.includes(model)) ||
checkSpecialVersion(line)
) {
modelSpecialDetected.push(line);
} else {
issueSpecialDetected.push(line);
}
}
response.status(200).send({
modelSpecial: modelSpecialDetected.join("\n"),
issueItem: issueSpecialDetected.join("\n"),
contentFile: processedData.join("\n"),
});
} catch (error) {
console.error("Error fetching log:", error);
response.status(203).send("FILE NOT FOUND");
}
}
public async getAllLogDetect({ response }: HttpContextContract) { public async getAllLogDetect({ response }: HttpContextContract) {
try { try {
const files = await LogDetectFile.all(); const files = await LogDetectFile.all();

View File

@ -95,7 +95,7 @@ Route.post("/api/backupProduct", async ({ request, response }) => {
PID: res.data[index].PID, PID: res.data[index].PID,
SN: res.data[index].SN, SN: res.data[index].SN,
VID: res.data[index].VID, VID: res.data[index].VID,
brand: res.data[index].brand, // brand: res.data[index].brand,
line: res.data[index].line.join(","), line: res.data[index].line.join(","),
file: res.data[index].fileName, file: res.data[index].fileName,
warehouse: res.data[index].warehouse, warehouse: res.data[index].warehouse,