Browse Source

日志文件时间分割,合并,异常捕获

hl 11 months ago
parent
commit
1fc41e746c
4 changed files with 82 additions and 37 deletions
  1. 13 9
      client.js
  2. 46 11
      src/utils/file.js
  3. 1 1
      src/utils/http.js
  4. 22 16
      src/web.js

+ 13 - 9
client.js

@@ -7,31 +7,35 @@ const {getRustConfig} = require("./src/config");
 const {logger} = require("./src/utils/logger");
 const {exec} = require("child_process");
 
-
-config.init()
-// 启动web
-web.init()
-// 定时任务
-interval.init()
+try {
+    config.init()
+    // 启动web
+    web.init()
+    // 定时任务
+    interval.init()
+} catch (e) {
+    logger.error(e.stack)
+    logger.error(e)
+}
 
 
 //node关机前的一些操作
 // 当进程即将退出时执行一些操作
 process.on('exit', (code) => {
-    console.log(`即将退出,退出码:${code}`);
+    logger.info(`即将退出,退出码:${code}`);
     // 在这里执行清理工作
 });
 
 // 监听SIGINT信号(例如用户按下Ctrl+C)
 process.on('SIGINT', () => {
-    console.log('收到SIGINT信号,准备退出...');
+    logger.info('收到SIGINT信号,准备退出...');
     // 在这里执行清理工作
     process.exit(); // 这将触发exit事件
 });
 
 // 监听SIGTERM信号(通常是系统请求进程终止)
 process.on('SIGTERM', async () => {
-    console.log('收到SIGTERM信号,准备退出...');
+    logger.info('收到SIGTERM信号,准备退出...');
     // 关机前为了防止 node 更新,需要吧map 里面的pid 写在本地文件
     await robot.closeAppAll()
 

+ 46 - 11
src/utils/file.js

@@ -68,16 +68,16 @@ function copyFileSync(source, destination) {
     }
 }
 
-// 读取日志(倒叙)指定行数
-function readLastNLines(filePath, n) {
-    const content = fs.readFileSync(filePath, 'utf8');
-    const lines = content.trim().split('\n');
-    const lastNLines = lines.slice(-n).join('\n');
-
-    // 此处处理或输出最后n行的内容
-    // console.log(lastNLines);
-    return lastNLines.split("\n").reverse();
-}
+// // 读取日志(倒叙)指定行数
+// function readLastNLines(filePath, n) {
+//     const content = fs.readFileSync(filePath, 'utf8');
+//     const lines = content.trim().split('\n');
+//     const lastNLines = lines.slice(-n).join('\n');
+//
+//     // 此处处理或输出最后n行的内容
+//     // console.log(lastNLines);
+//     return lastNLines.split("\n").reverse();
+// }
 
 
 // 下载文件
@@ -87,7 +87,41 @@ function dowFile(url, fileName, dowPath, headers) {
 
 // 删除文件
 function delFile() {
+}
+
+/***********************************/
+function getLastFile(dirPath, number, callback) {
+    fs.readdir(dirPath, async (err, files) => {
+        if (err) {
+            console.error(`Could not list the directory.`, err);
+            process.exit(1);
+        }
+        let fileList = [];
+        for (file of files) {
+            const filePath = path.join(dirPath, file);
+            const stats = await fs.promises.stat(filePath);
+            fileList.push({ name: file, time: stats.mtimeMs });
+        }
+        fileList.sort((a, b) => b.time - a.time);
+        lastFileList = fileList.slice(0, number != -1 ? number : fileList.length);
+        lastFileNameList = lastFileList.map((item) => item.name);
+        callback(lastFileNameList.reverse(), lastFileList.reverse());
+    });
+}
 
+// 读取日志(倒叙)指定行数
+function readLastNLines(dirPath, filePathList, n) {
+    const fileList = filePathList.map((item) => {
+        const content = fs.readFileSync(`${dirPath}/${item}`, "utf8");
+        const lines = content.trim().split("\n");
+        return {
+            filePath: item,
+            lines: lines,
+        };
+    });
+    const allFile = [].concat(...fileList.map((item) => item.lines));
+    const lastNLines = allFile.slice(-n).join("\n");
+    return lastNLines.split("\n").reverse();
 }
 
 
@@ -97,5 +131,6 @@ module.exports = {
     checkPathSync,
     writeFile,
     copyFileSync,
-    readLastNLines
+    readLastNLines,
+    getLastFile
 }

+ 1 - 1
src/utils/http.js

@@ -145,5 +145,5 @@ function dowFile(url, fileName, dowPath, headers) {
 module.exports = {
     request_get,
     request_post,
-    dowFile
+    dowFile,
 };

+ 22 - 16
src/web.js

@@ -32,23 +32,29 @@ function init() {
         const id = param.id
 
         //时间
-        const today = new Date();
-        const year = today.getFullYear(); // 获取年份
-        const month = (today.getMonth() + 1).toString().padStart(2, '0');
-        const day = today.getDate().toString().padStart(2, '0');
-        // 拼接字符串得到 YYYY-MM-DD 格式
-        var logName = `${year}-${month}-${day}`;
+        // const today = new Date();
+        // const year = today.getFullYear(); // 获取年份
+        // const month = (today.getMonth() + 1).toString().padStart(2, '0');
+        // const day = today.getDate().toString().padStart(2, '0');
+        // // 拼接字符串得到 YYYY-MM-DD 格式
+        // var logName = `${year}-${month}-${day}`;
+        //
+        // var f = getRustConfig().logPath + "/" + logName + ".log"
+        // var array = [];
+        // if (file.checkFilePath(f)) {
+        //     const directoryPath = path.resolve(f);
+        //     array = file.readLastNLines(directoryPath, n)
+        // } else {
+        //     logger.info('日志文件不存在:' + f);
+        // }
 
-        var f = getRustConfig().logPath + "/" + logName + ".log"
-        var array = [];
-        if (file.checkFilePath(f)) {
-            const directoryPath = path.resolve(f);
-            array = file.readLastNLines(directoryPath, n)
-        } else {
-            logger.info('日志文件不存在:' + f);
-        }
-
-        res.send({'code': 200, 'data': array, "message": "SUCCESS"});
+        let result = [];
+        file.getLastFile(getRustConfig().logPath, 10, (fileNameList) => {
+            logger.info('??:' ,fileNameList);
+            result = file.readLastNLines(getRustConfig().logPath, fileNameList, n);
+            logger.info('?????:' ,result);
+            res.send({'code': 200, 'data': result, "message": "SUCCESS"});
+        });
     });
     app.post('/execute', (req, res) => {
         // 获取发送过来的信息(请求体的数据)