@Service public class AccessLogCleanTimer { Logger logger= LoggerFactory.getLogger(AccessLogCleanTimer.class); private ServerProperties serverProperties; @Autowired private void setSServerProperties(ServerProperties serverProperties){ this.serverProperties=serverProperties; } @Scheduled(cron="0 1 23 ? * 5L") public void cleanTimer(){ logger.info("开始清理tomcat accessLog"); String logPath = serverProperties.getTomcat().getBasedir().getAbsolutePath()+"/logs"; if (new File(logPath).isDirectory()) { // 获取文件夹中的文件集合 File[] logs = new File(logPath).listFiles(); // 设置系统这里设置的日期格式,和配置文件里的参数保持一致 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 遍历集合 for (int i = 0; i < logs.length; i++) { File log = logs[i]; // 获取到第i个日志的名称,截取中间的日期字段,转成long型s int start = log.getName().indexOf(".") + 1; int end = log.getName().lastIndexOf("."); // 获取到的日志名称中的时间(2016-12-16) String dateStr = log.getName().substring(start, end); // 将字符串型的(2016-12-16)转换成long型 long lonInt = 0; try { lonInt = dateFormat.parse(dateStr).getTime(); // 系统时间减去日志名字中获取的时间差大于配置文件中设置的时间删除 if ((System.currentTimeMillis() - lonInt) / (1000 * 60 * 60 * 24) > 30) { log.delete(); System.out.println(log.getName()); } } catch (ParseException e) { logger.error("删除accessLog出错",e); } } } } }
目前没找到合适的配置自动清除方法,只能手动清除
扫描二维码关注公众号,回复:
4758636 查看本文章