package com.system.log.service; import Log.LogEntity; import Log.repo.LogEntityRepository; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.google.inject.Inject; import com.hypaas.rpc.ActionRequest; import com.hypaas.rpc.ActionResponse; import com.system.log.LogTypeEnum; import com.system.log.vo.LogRecordVO; import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.util.Zip4jConstants; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class LogService { @Inject LogEntityRepository logEntityRepository; public JSONObject getDirContent(String logType, String startTime, String endTime, String keyWord) throws IOException { // 定义集合,存放文件名称 List fileList; // 获取Tomcat的CATALINA_BASE属性 String catalinaBase = System.getProperty("catalina.base"); // 获取localhost_access_log所在文件目录 String accessLogDir = catalinaBase + "\\logs"; // 找到过滤出的localhost_access_log文件,将文件的绝对路径放入集合中 fileList = getFilePath(accessLogDir, startTime, endTime); // 获取所有文件下符合过滤条件内容并返回 return getFileContent(fileList, logType, startTime, endTime, keyWord); } // 找出文件夹下指定日志文件名并返回 private List getFilePath(String accessLogDir, String startTime, String endTime) { // 定义集合,存放当前符合筛选条件的文件名 List filePathList = new ArrayList<>(); // 如果不传开始时间与结束时间,指定为null即可,默认输出当天的日志 if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) { // 以yyyy-MM-dd格式获取当天日期 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String date = simpleDateFormat.format(new Date(System.currentTimeMillis())); File LogFile = new File(accessLogDir); File[] file = LogFile.listFiles(); for (File file1 : file) { if (file1.toString().contains("localhost_access_log") && file1.toString().contains(date)) { // 如果此文件是localhost_access_log文件并且是当天的文件,将其放入集合返回 filePathList.add(file1.getPath()); return filePathList; } } } else { filePathList = getFile(accessLogDir, startTime, endTime); } return filePathList; } // 使用日历类将符合条件的日志文件放入集合中返回 private List getFile(String accessLogDir, String startTime, String endTime) { // 获取传入的开始时间与结束时间的毫秒数,开始时间直接将时分秒置零处理,结束时间将其加上一天后再将其置零处理, // 这样做的目的是保证取出符合本次过滤时间的所有文件 List fileList = new ArrayList<>(); long[] time = getZeroLongTime(startTime, endTime); // 遍历指定目录中的文件,筛选出符合条件的日志文件 File LogFile = new File(accessLogDir); File[] file = LogFile.listFiles(); for (File file1 : file) { if (file1.toString().contains("localhost_access_log")) { // 如果文件名包含"localhost_access_log",则判断时间是否符合要求,如果符合,放入集合中 if ((getFileLongTime(file1.toString()) + 1000 > time[0]) && (getFileLongTime(file1.toString()) + 1000 < time[1])) { fileList.add(file1.getPath()); } } } return fileList; } // 获取文件名中的时间毫秒值 private long getFileLongTime(String fileName) { Date date; long milliseconds = 0; String regex = "\\d{4}-\\d{2}-\\d{2}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(fileName); if (matcher.find()) { String time = matcher.group(0); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { date = simpleDateFormat.parse(time); } catch (ParseException e) { throw new RuntimeException(e); } milliseconds = date.getTime(); } return milliseconds; } // 输入开始时间与结束时间获得对应的零点毫秒数,方便筛选日志文件,必须以"yyyy-MM-dd HH:mm:ss"的形式输入 private long[] getZeroLongTime(String startTime, String endTime) { // 用于存放毫秒数结果的数组 long[] longTime = new long[2]; Calendar calendar = Calendar.getInstance(); // 开始处理开始时间,得到毫秒值 calendar.set(Calendar.YEAR, Integer.parseInt(startTime.substring(0, 4))); // 日历类中,00表示1月, 01表示2月,故应该减1 calendar.set(Calendar.MONTH, Integer.parseInt(startTime.substring(5, 7)) - 1); calendar.set(Calendar.DATE, Integer.parseInt(startTime.substring(8, 10))); // 这是将当天的【秒】设置为0 calendar.set(Calendar.SECOND, 0); // 这是将当天的【分】设置为0 calendar.set(Calendar.MINUTE, 0); // 这是将当天的【时】设置为0 calendar.set(Calendar.HOUR_OF_DAY, 0); longTime[0] = calendar.getTimeInMillis(); // 开始处理结束时间,得到毫秒值 calendar.set(Calendar.YEAR, Integer.parseInt(endTime.substring(0, 4))); calendar.set(Calendar.MONTH, Integer.parseInt(endTime.substring(5, 7)) - 1); calendar.set(Calendar.DATE, Integer.parseInt(endTime.substring(8, 10)) + 1); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); longTime[1] = calendar.getTimeInMillis(); return longTime; } // 输入开始时间与结束时间获得对应的标准毫秒数,方便筛选每个日志文件中的数据,必须以"yyyy-MM-dd HH:mm:ss"的形式输入 private long getLongTime(String time) { Date date; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { date = simpleDateFormat.parse(time); } catch (ParseException e) { throw new RuntimeException(e); } return date.getTime(); } // 获取 private long getLogContentLongTime(String logContent) { Date date; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", Locale.ENGLISH); try { // 取出日志文件中例如22/Feb/2024:10:04:32 +0800的部分,转化为毫秒 date = simpleDateFormat.parse( logContent.substring(logContent.indexOf("[") + 1, logContent.indexOf("[") + 21)); } catch (ParseException e) { throw new RuntimeException(e); } return date.getTime(); } // 返回日志文件的详细内容(StringBuffer) private JSONObject getFileContent( List fileList, String logType, String startTime, String endTime, String keyWord) { JSONArray jsonArray = new JSONArray(); if (StringUtils.isEmpty(logType)) { logType = ""; } if (StringUtils.isEmpty(keyWord)) { keyWord = ""; } for (String file : fileList) { try { // 设置读取器,读取fileList中的文件 BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); String line; // 如果开始时间与结束时间为空,则fileList里只有一个当天的日志文件,不需要时间过滤,只过滤日志类型与关键字即可 if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) { // 判断下一行不为空就读取出来进行条件判断 while ((line = bufferedReader.readLine()) != null) { // 判断本行数据是否包含输入的日志类型与关键字信息,如果包含,写入文件 if (LogTypeEnum.Interface.getValue().equals(logType)) { if ((!line.contains(LogTypeEnum.Exception.getValue())) && line.contains(keyWord)) { jsonArray.add(logAnalysis(line, file)); } } else { if (line.contains(logType) && line.contains(keyWord)) { jsonArray.add(logAnalysis(line, file)); } } } } else { // 如果开始时间与结束时间不为空,则fileList里不确定有几个日志文件,由于考虑精确到时分秒,需要时间过滤, // 还需要过滤日志类型与关键字 while ((line = bufferedReader.readLine()) != null) { if (LogTypeEnum.Interface.getValue().equals(logType)) { if (getLongTime(startTime) <= getLogContentLongTime(line) && getLongTime(endTime) >= getLogContentLongTime(line) && ((!line.contains(LogTypeEnum.Exception.getValue())) && line.contains(keyWord))) { jsonArray.add(logAnalysis(line, file)); } } else { if (getLongTime(startTime) <= getLogContentLongTime(line) && getLongTime(endTime) >= getLogContentLongTime(line) && (line.contains(logType) && line.contains(keyWord))) { jsonArray.add(logAnalysis(line, file)); } } } } } catch (Exception e) { e.getStackTrace(); } } JSONObject jsonObject = new JSONObject(); JSONObject selectContent = new JSONObject(); jsonObject.put("code", 200); jsonObject.put("msg", "操作成功"); selectContent.put("content", jsonArray); jsonObject.put("data", selectContent); return jsonObject; } // 解析日志,提取关键信息 private JSONObject logAnalysis(String logContent, String fileName) { JSONObject logDetail = new JSONObject(); LogRecordVO logRecordVO = new LogRecordVO(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", Locale.ENGLISH); try { // 以yyyy-MM-dd HH:mm:ss形式提取时间 long l = simpleDateFormat .parse( logContent.substring(logContent.indexOf("[") + 1, logContent.indexOf("[") + 21)) .getTime(); SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = simpleDateFormat1.format(l); logRecordVO.setTime(date); // 提取ip地址 String ipAddress = logContent.substring(0, logContent.indexOf("-") - 1); logRecordVO.setIpAddress(ipAddress); // 写入文件名l logRecordVO.setFileSource(fileName); // 写入文件内容 String log = logContent.substring(logContent.indexOf("]") + 2, logContent.length()).replace("\"", ""); logRecordVO.setLogContent(log); return (JSONObject) JSONObject.toJSON(logRecordVO); } catch (ParseException e) { throw new RuntimeException(e); } } public File getFileZip(ActionRequest request, ActionResponse response) { String password = request.getContext().get("password").toString(); String confirmPassword = request.getContext().get("confirmPassword").toString(); String startTime = request.getContext().get("startTime").toString(); String endTime = request.getContext().get("endTime").toString(); String logType = request.getContext().get("logType").toString(); String keyWord = request.getContext().get("keyWord").toString(); // 判断密码和确认密码是否都不为空且一致,如果不一致直接返回null if (StringUtils.isEmpty(password) || StringUtils.isEmpty(confirmPassword) || !password.equals(confirmPassword)) { return null; } // 定义集合,存放文件名称 List fileList; // 获取Tomcat的CATALINA_BASE属性 String catalinaBase = System.getProperty("catalina.base"); // 获取localhost_access_log所在文件目录 String accessLogDir = catalinaBase + "\\logs"; // 找到过滤出的localhost_access_log文件,将文件的绝对路径放入集合中 fileList = getFilePath(accessLogDir, startTime, endTime); // 查询出所有的记录 JSONObject selectResult = getFileContent(fileList, logType, startTime, endTime, keyWord); try { // 创建临时文件,将查询的结果写入临时文件 File tempFile = File.createTempFile("log", ".txt"); FileWriter writer = new FileWriter(tempFile); writer.write(selectResult.toString()); writer.close(); // 根据时间设定输出文件名 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); String date = simpleDateFormat.format(new Date(System.currentTimeMillis())); // 获取临时文件目录 String tempDir = System.getProperty("java.io.tmpdir"); String tempFilePath = tempDir + "/" + date + ".zip"; System.out.println(tempFilePath); // 在临时文件目录中创建一个随机名称的zip文件 File file = new File(tempFilePath); ZipFile zipFile = new ZipFile(file); ZipParameters parameters = new ZipParameters(); // 设置zip包的一些参数集合 parameters.setEncryptFiles(true); // 是否设置密码(此处设置为:是) parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式(默认值) parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 普通级别(参数很多) parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密级别 parameters.setPassword(password); // 压缩包密码 // 向zip文件中根据设置的参数写入数据 zipFile.createZipFile(tempFile, parameters); return file; } catch (ZipException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } // public JSONObject getFileChange() { // // 定义集合,存放文件名称 // List fileList; // // 获取Tomcat的CATALINA_BASE属性 // String catalinaBase = System.getProperty("catalina.base"); // // 获取localhost_access_log所在文件目录 // String accessLogDir = catalinaBase + "\\logs"; // // 找到过滤出的localhost_access_log文件,将文件的绝对路径放入集合中 // fileList = getFilePath(accessLogDir, null, null); // // 返回当天日志文件 // return getFileContent(fileList, null, null, null, null); // } public File exportLog(ActionRequest request, ActionResponse response) throws IOException { String password = request.getContext().get("password").toString(); String confirmPassword = request.getContext().get("confirmPassword").toString(); String startTime = request.getContext().get("exportStartTime").toString(); String endTime = request.getContext().get("exportEndTime").toString(); if (!password.equals(confirmPassword)) { response.setAlert("两次输入的密码不一致!"); return null; } // 密码正则表达式校验 String regex = "^(?![0-9A-Za-z]+$)(?![0-9A-Z\\W]+$)(?![0-9a-z\\W]+$)(?![A-Za-z\\W]+$)[0-9A-Za-z~!@#$%^&*()_+`\\-={}|\\[\\]\\\\:\";'<>?,./]{6,16}$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(password); if (!matcher.find()) { // 密码不通过正则校验 response.setAlert("密码需要包含6-16位数字+大写字母+小写字母+特殊字符!"); return null; } List selectResult = new ArrayList<>(); List logEntitiesList = logEntityRepository.all().fetch(); if (startTime != null && endTime != null) { // 如果输入的开始时间与结束时间都不为空,则输出时间范围内的所有记录 for (LogEntity logEntity : logEntitiesList) { if ((getSqlLongTime(logEntity.getTime()) > getSqlLongTime(startTime)) && (getSqlLongTime(logEntity.getTime()) < getSqlLongTime(endTime))) { selectResult.add(logEntity); } } } if (startTime == null && endTime != null) { // 如果输入的开始时间为空,则输出结束时间之前的所有记录 for (LogEntity logEntity : logEntitiesList) { if ((getSqlLongTime(logEntity.getTime()) < getSqlLongTime(endTime))) { selectResult.add(logEntity); } } } if (startTime != null && endTime == null) { // 如果输入的结束时间为空,则输出开始时间之后的所有记录 for (LogEntity logEntity : logEntitiesList) { if ((getSqlLongTime(logEntity.getTime()) > getSqlLongTime(startTime))) { selectResult.add(logEntity); } } } if (startTime == null && endTime == null) { // 如果输入的时间都为空,则输出所有记录 for (LogEntity logEntity : logEntitiesList) { selectResult.add(logEntity); } } // Object jsonObject = JSONObject.toJSON(selectResult); return exportLogExcelZip(selectResult, password); } private long getSqlLongTime(Object time) { // logEntity.getTime()形式 "2024-02-04T14:03:45.114" // startTime()形式 "2024-02-04 14:03" Date date; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (time.toString().length() < 19) { time = time.toString().replace("T", " ") + ":00"; } else { time = time.toString().substring(0, 19).replace("T", " "); } try { date = simpleDateFormat.parse(time.toString()); } catch (ParseException e) { throw new RuntimeException(e); } return date.getTime(); } // 导出为Excel类型 public File exportLogExcelZip(List selectResult, String password) throws IOException { // 创建一个工作簿,也就是Excel文件 HSSFWorkbook wb = new HSSFWorkbook(); // 创建一个工作表 HSSFSheet sheet = wb.createSheet(); // 第一行,标题 HSSFRow row0 = sheet.createRow(0); HSSFCell cell0 = row0.createCell(0); cell0.setCellValue("操作日志表"); // 第二行,表头 HSSFRow row1 = sheet.createRow(1); row1.createCell(0).setCellValue("id"); row1.createCell(1).setCellValue("address"); row1.createCell(2).setCellValue("content"); row1.createCell(3).setCellValue("hashValue"); row1.createCell(4).setCellValue("levelDesc"); row1.createCell(5).setCellValue("levelNum"); row1.createCell(6).setCellValue("module"); row1.createCell(7).setCellValue("objectName"); row1.createCell(8).setCellValue("opType"); row1.createCell(9).setCellValue("result"); row1.createCell(10).setCellValue("resultDesc"); row1.createCell(11).setCellValue("status"); row1.createCell(12).setCellValue("time"); row1.createCell(13).setCellValue("userAuth"); row1.createCell(14).setCellValue("userAuthDesc"); row1.createCell(15).setCellValue("userId"); // 向表中写入数据 int rowInt = 2; for (LogEntity logEntity : selectResult) { HSSFRow row = sheet.createRow(rowInt++); int index = 0; row.createCell(index++).setCellValue(logEntity.getId()); row.createCell(index++).setCellValue(logEntity.getAddress()); row.createCell(index++).setCellValue(logEntity.getContent()); row.createCell(index++).setCellValue(logEntity.getHashValue()); row.createCell(index++).setCellValue(logEntity.getLevelDesc()); row.createCell(index++).setCellValue(logEntity.getLevelNum().getValue()); row.createCell(index++).setCellValue(logEntity.getModule()); row.createCell(index++).setCellValue(logEntity.getObjectName()); row.createCell(index++).setCellValue(logEntity.getOpType().getValue()); row.createCell(index++).setCellValue(logEntity.getResult()); row.createCell(index++).setCellValue(logEntity.getResultDesc()); row.createCell(index++).setCellValue(logEntity.getStatus()); row.createCell(index++).setCellValue(logEntity.getTime().toString()); row.createCell(index++).setCellValue(logEntity.getUserAuth().getValue()); row.createCell(index++).setCellValue(logEntity.getUserAuthDesc()); row.createCell(index++).setCellValue(logEntity.getUserId()); } FileOutputStream fos = null; try { // 输出文件,创建字节输出流 File tempFile = new File(File.createTempFile("log", ".xls").getPath()); fos = new FileOutputStream(tempFile); wb.write(fos); fos.flush(); // 根据时间设定输出文件名 SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); String date = simpleDateFormat1.format(new Date(System.currentTimeMillis())); // 获取临时文件目录 String tempDir = System.getProperty("java.io.tmpdir"); String tempFilePath = tempDir + "/" + date + ".zip"; System.out.println(tempFilePath); // 在临时文件目录中创建一个随机名称的zip文件 File file = new File(tempFilePath); ZipFile zipFile = new ZipFile(file); ZipParameters parameters = new ZipParameters(); // 设置zip包的一些参数集合 parameters.setEncryptFiles(true); // 是否设置密码(此处设置为:是) parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式(默认值) parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 普通级别(参数很多) parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密级别 parameters.setPassword(password); // 压缩包密码 // 向zip文件中根据设置的参数写入数据 zipFile.createZipFile(tempFile, parameters); return file; } catch (ZipException e) { throw new RuntimeException(e); } finally { fos.close(); } } public File exportLogZip(Object selectResult, String password) { try { // 创建临时文件,将查询的结果写入临时文件 File tempFile = File.createTempFile("log", ".txt"); FileWriter writer = new FileWriter(tempFile); writer.write(selectResult.toString()); writer.close(); // 根据时间设定输出文件名 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); String date = simpleDateFormat.format(new Date(System.currentTimeMillis())); // 获取临时文件目录 String tempDir = System.getProperty("java.io.tmpdir"); String tempFilePath = tempDir + "/" + date + ".zip"; System.out.println(tempFilePath); // 在临时文件目录中创建一个随机名称的zip文件 File file = new File(tempFilePath); ZipFile zipFile = new ZipFile(file); ZipParameters parameters = new ZipParameters(); // 设置zip包的一些参数集合 parameters.setEncryptFiles(true); // 是否设置密码(此处设置为:是) parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式(默认值) parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 普通级别(参数很多) parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密级别 parameters.setPassword(password); // 压缩包密码 // 向zip文件中根据设置的参数写入数据 zipFile.createZipFile(tempFile, parameters); return file; } catch (ZipException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }