package com.system.log.service; import Log.LogBackup; import Log.LogConfig; import Log.LogEntity; import Log.repo.LogBackupRepository; import Log.repo.LogConfigRepository; import Log.repo.LogEntityRepository; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.google.inject.Inject; import com.google.inject.persist.Transactional; import com.hypaas.db.JPA; 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.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import module.LogStatus; 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; @Inject LogConfigRepository logConfigRepository; @Inject LogBackupRepository logBackupRepository; 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"的形式输入 public 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, String userAuth) 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)) && userAuth.equals(logEntity.getUserAuth().getValue())) { selectResult.add(logEntity); } } } if (startTime == null && endTime != null) { // 如果输入的开始时间为空,则输出结束时间之前的符合用户角色的所有记录 for (LogEntity logEntity : logEntitiesList) { if ((getSqlLongTime(logEntity.getTime()) < getSqlLongTime(endTime)) && userAuth.equals(logEntity.getUserAuth().getValue())) { selectResult.add(logEntity); } } } if (startTime != null && endTime == null) { // 如果输入的结束时间为空,则输出开始时间之后的符合用户角色的所有记录 for (LogEntity logEntity : logEntitiesList) { if ((getSqlLongTime(logEntity.getTime()) > getSqlLongTime(startTime)) && userAuth.equals(logEntity.getUserAuth().getValue())) { selectResult.add(logEntity); } } } if (startTime == null && endTime == null) { // 如果输入的时间都为空,则输出符合用户角色的所有记录 for (LogEntity logEntity : logEntitiesList) { if (userAuth.equals(logEntity.getUserAuth().getValue())) { selectResult.add(logEntity); } } } // Object jsonObject = JSONObject.toJSON(selectResult); return exportLogExcelZip(selectResult, password); } public 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); } } public JSONObject setLogConfig(Integer threshold, Integer backupCycle, String backupStartTime) { List logBackupList = logBackupRepository.all().fetch(); if (logBackupList.size() == 0) { LogBackup logBackup = new LogBackup(); logBackup.setBackupCycle(backupCycle); logBackup.setThreshold(threshold); logBackup.setBackupStartTime(backupStartTime); saveBackup(logBackup); } else { LogBackup logBackupSelectResult = logBackupRepository.find(logBackupList.get(0).getId()); logBackupSelectResult.setBackupCycle(backupCycle); logBackupSelectResult.setThreshold(threshold); logBackupSelectResult.setBackupStartTime(backupStartTime); saveBackup(logBackupSelectResult); } LogConfig logConfig = new LogConfig(); logConfig.setThreshold(threshold); logConfig.setBackupCycle(backupCycle); logConfig.setStatus(LogStatus.waitBackup); // 起始备份时间为手动输入的备份开始时间,结束时间需要通过备份周期计算 logConfig.setLogStartTime(backupStartTime); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); Date date = null; String logEndTime = null; try { date = simpleDateFormat.parse(backupStartTime); calendar.setTime(date); calendar.add(Calendar.DAY_OF_YEAR, backupCycle); Long longTime = calendar.getTime().getTime(); // 将日志结束时间转化为"yyyy-MM-dd HH:mm:ss"格式 logEndTime = simpleDateFormat.format(longTime); } catch (ParseException e) { throw new RuntimeException(e); } logConfig.setLogEndTime(logEndTime); List list = logConfigRepository.all().fetch(); if (list.size() != 0) { // 说明已经有记录了,要先将原来的主配置找到改为历史配置 for (LogConfig config : list) { if ("Current".equals(config.getRecordType())) { LogConfig logConfig1 = logConfigRepository.find(config.getId()); logConfig1.setRecordType("History"); saveConfig(logConfig1); break; } } } logConfig.setRecordType("Current"); saveConfig(logConfig); JSONObject jsonObject = new JSONObject(); jsonObject.put("code", 200); jsonObject.put("msg", "保存成功"); return jsonObject; } @Transactional public LogConfig saveConfig(LogConfig entity) { return JPA.save(entity); } @Transactional public LogBackup saveBackup(LogBackup entity) { return JPA.save(entity); } public void deleteSystemManageUserBackup(ActionRequest request, ActionResponse response) { Long id = (Long) request.getContext().get("id"); LogConfig logConfig = logConfigRepository.find(id); if (null == logConfig) { response.setError("未查询到此条记录"); return; } String filePath = logConfig.getFilePath(); File file = new File(filePath + "systemManageUser.zip"); // if (file.delete()) { // logConfig.setStatus(LogStatus.alreadyDelete); // response.setNotify("日志备份文件删除成功!"); // saveConfig(logConfig); // response.setReload(true); // } else { // response.setError("日志备份文件删除失败!"); // response.setReload(true); // } file.delete(); logConfig.setStatus(LogStatus.alreadyDelete); response.setNotify("日志备份文件删除成功!"); saveConfig(logConfig); response.setReload(true); } public void secondBackup(ActionRequest request, ActionResponse response) { Long id = (Long) request.getContext().get("id"); LogConfig logConfig = logConfigRepository.find(id); if (null == logConfig) { response.setError("未查询到此条记录"); response.setReload(true); return; } if (!LogStatus.backupFail.getValue().equals(logConfig.getStatus().getValue())) { response.setNotify("该条记录状态非备份失败"); response.setReload(true); return; } String backupTime = null; String filePath = null; try { filePath = backupLogExcelZip(selectRecord(logConfig)); } catch (IOException e) { response.setError("重新备份失败!"); response.setReload(true); throw new RuntimeException(e); } // 需要将状态改为已备份,并添加备份时间,计算备份大小,将当前配置改为历史配置 logConfig.setStatus(LogStatus.alreadyBackup); backupTime = getStringTime(System.currentTimeMillis()); logConfig.setBackupStartTime(backupTime); logConfig.setBackupTime(backupTime); // 计算文件大小,单位以M表示,精确小数点后两位 Map fileSizeMap = getSize(filePath); logConfig.setThresholdSystemManageUserSize(fileSizeMap.get("1")); logConfig.setThresholdSecurityUserSize("2"); logConfig.setThresholdSecurityAuditUserSize("3"); logConfig.setThresholdServiceUserSize("4"); logConfig.setFilePath(filePath); if (logConfig.getRecordType().equals("Current")) { logConfig.setRecordType("History"); // 如果是当前配置,要添加一条新的记录,将记录改为待配置,因为当前是主配置,历史配置的话不需要,备份一次即可 LogConfig newRecord = new LogConfig(); newRecord.setRecordType("Current"); // 日志开始时间就是上次备份时间,根据备份周期计算日志结束时间 newRecord.setLogStartTime(backupTime); newRecord.setLogEndTime(getEndTime(backupTime, logConfig.getBackupCycle())); newRecord.setStatus(LogStatus.waitBackup); logConfigRepository.save(newRecord); } saveConfig(logConfig); response.setReload(true); } public Map> selectRecord(LogConfig logConfig) { Map> map = new HashMap<>(); List serviceUserSelectResult = new ArrayList<>(); List securityUserSelectResult = new ArrayList<>(); List securityAuditUserSelectResult = new ArrayList<>(); List systemManageUserResult = new ArrayList<>(); List logEntityList = logEntityRepository.all().fetch(); for (LogEntity logEntity : logEntityList) { if (getSqlLongTime(logEntity.getTime()) > getLongTime(logConfig.getLogStartTime()) && getSqlLongTime(logEntity.getTime()) < getLongTime(logConfig.getLogEndTime())) { // 如果当条记录时间大于开始时间小于结束时间,则判断角色 if (logEntity.getUserAuth().getValue().equals("1")) { // 系统管理员 systemManageUserResult.add(logEntity); } if (logEntity.getUserAuth().getValue().equals("2")) { // 安全保密员 securityUserSelectResult.add(logEntity); } if (logEntity.getUserAuth().getValue().equals("3")) { // 安全审计员 securityAuditUserSelectResult.add(logEntity); } if (logEntity.getUserAuth().getValue().equals("4")) { // 业务用户 serviceUserSelectResult.add(logEntity); } map.put("systemManageUser", systemManageUserResult); map.put("securityUser", securityUserSelectResult); map.put("securityAuditUser", securityAuditUserSelectResult); map.put("serviceUser", serviceUserSelectResult); } } return map; } // 备份日志,导出为Excel类型 public String backupLogExcelZip(Map> selectResult) throws IOException { String tempFilePath = null; Set>> entries = selectResult.entrySet(); // 根据时间设定输出文件名 SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS"); String date = simpleDateFormat1.format(new Date(System.currentTimeMillis())); for (Map.Entry> entry : entries) { // 创建一个工作簿,也就是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 : entry.getValue()) { 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(); // 获取临时文件目录 String tempDir = System.getProperty("java.io.tmpdir"); tempFilePath = tempDir + "\\" + date; String realFilePath = tempDir + "\\" + date + entry.getKey() + ".zip"; // 在临时文件目录中创建一个随机名称的zip文件 File file = new File(realFilePath); 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); // 加密级别 // 向zip文件中根据设置的参数写入数据 zipFile.createZipFile(tempFile, parameters); } catch (ZipException e) { throw new RuntimeException(e); } finally { fos.close(); } } return tempFilePath; } public String getStringTime(long time) { SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return simpleDateFormat1.format(time); } public String getEndTime(String time, Integer backupCycle) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); Date date = null; String logEndTime = null; try { date = simpleDateFormat.parse(time); calendar.setTime(date); calendar.add(Calendar.DAY_OF_YEAR, backupCycle); Long longTime = calendar.getTime().getTime(); // 将日志结束时间转化为"yyyy-MM-dd HH:mm:ss"格式 logEndTime = simpleDateFormat.format(longTime); return logEndTime; } catch (ParseException e) { throw new RuntimeException(e); } } public Map getSize(String filePath) { Map map = new HashMap<>(); map.put("1", getFileSize(filePath + "systemManageUser.zip")); map.put("2", getFileSize(filePath + "securityUser.zip")); map.put("3", getFileSize(filePath + "securityAuditUser.zip")); map.put("4", getFileSize(filePath + "serviceUser.zip")); return map; } // 计算文件大小,单位为M,保留两位小数 public String getFileSize(String filePath) { File file = new File(filePath); long fileSize = file.length(); DecimalFormat df = new DecimalFormat("#.00"); // 将字节转换为兆字节(MB)并格式化输出 double fileSizeInKB = (double) fileSize / 1024; if (fileSizeInKB > 1024) { double fileSizeInMB = (double) fileSize / (1024 * 1024); if (fileSizeInMB > 1024) { double fileSizeInGB = (double) fileSize / (1024 * 1024 * 1024); String formattedNumber = df.format(fileSizeInGB); double result = Double.parseDouble(formattedNumber); return result + "GB"; } String formattedNumber = df.format(fileSizeInMB); double result = Double.parseDouble(formattedNumber); return result + "MB"; } String formattedNumber = df.format(fileSizeInKB); double result = Double.parseDouble(formattedNumber); return result + "KB"; } public JSONObject selectLogConfig() { JSONObject jsonObject = new JSONObject(); jsonObject.put("code", 200); jsonObject.put("msg", "操作成功"); List logBackupList = logBackupRepository.all().fetch(); if (logBackupList.size() == 0) { jsonObject.put("data", null); return jsonObject; } else { JSONObject selectResult = new JSONObject(); selectResult.put("threshold", logBackupList.get(0).getThreshold()); selectResult.put("backupCycle", logBackupList.get(0).getBackupCycle()); selectResult.put("backupStartTime", logBackupList.get(0).getBackupStartTime()); jsonObject.put("data", selectResult); return jsonObject; } } }