This commit is contained in:
777
2025-12-22 10:18:01 +08:00
parent c7bdea46d0
commit 35fe4b005f
3 changed files with 141 additions and 0 deletions

View File

@@ -0,0 +1,77 @@
package com.ruoyi.cai.util;
import com.ruoyi.common.exception.base.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.exec.*;
import org.apache.commons.exec.environment.EnvironmentUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
public class LoginLogByFileUtil {
public static List<String> getLog(String mobile){
// 1. 定义命令带管道的Linux命令需用/bin/sh -c包裹
String commandFormat = "tac /home/server/api/logs/sys-console.log | grep \"%s\" | grep -m 10 \"auth/login\"";
String command = String.format(commandFormat, mobile);
CommandLine cmdLine = CommandLine.parse("/bin/sh -c " + command); // 自动处理参数分隔
// 2. 配置执行器(设置超时、流处理)
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(0); // 期望的退出码0表示成功
// 设置进程超时5秒适配你的快速执行场景
ExecuteWatchdog watchdog = new ExecuteWatchdog(5000); // 5000ms = 5s
executor.setWatchdog(watchdog);
// 3. 处理输出ByteArrayOutputStream存储10行结果或用PumpStreamHandler实时处理
// 场景1存储结果到内存仅10行内存无压力
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputStream); // 合并标准输出/错误流
executor.setStreamHandler(streamHandler);
// 场景2实时处理每行输出推荐避免存储
// PumpStreamHandler streamHandler = new PumpStreamHandler(new LogOutputStream() {
// @Override
// protected void processLine(String line, int level) {
// // 实时处理每行数据(如输出到前端、写入日志)
// System.out.println(line);
// }
// });
// executor.setStreamHandler(streamHandler);
try {
// 4. 执行命令(环境变量使用系统默认,可自定义)
Map<String, String> env = EnvironmentUtils.getProcEnvironment();
executor.execute(cmdLine, env);
// 5. 解析结果场景1的方式
String result = outputStream.toString(StandardCharsets.UTF_8.name());
String[] split = result.split(System.lineSeparator());
List<String> lines = Arrays.stream(split).collect(Collectors.toList());
System.out.println("匹配的行数:" + lines.size());
lines.forEach(System.out::println);
} catch (ExecuteException e) {
if (watchdog.killedProcess()) {
log.error("命令执行超时,已终止进程");
} else {
log.error("命令执行失败,退出码:" + e.getExitValue());
}
log.error(e.getMessage(),e);
throw new BaseException("命令执行失败");
} catch (IOException e) {
log.error("IO异常" + e.getMessage());
log.error(e.getMessage(),e);
throw new BaseException("IO异常");
}
return Collections.emptyList();
}
}