package com.yanzuoguang.log; import com.yanzuoguang.util.cache.MemoryCache; import com.yanzuoguang.util.helper.DateHelper; import com.yanzuoguang.util.helper.StringHelper; import com.yanzuoguang.util.thread.ThreadNext; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * 日志时间 * * @author 颜佐光 */ @Component public class LogCountTime implements ThreadNext.Next, InitializingBean { private static final String URL_PARA_START = "?"; private final LogConfig logConfig; private final LogBase logBase; /** * 今日缓存,超过时间会自动清空 */ private final MemoryCache todayMemoryCache = new MemoryCache<>(); /** * 今日日期 */ private String today; public LogCountTime(LogConfig logConfig, LogBase logBase) { this.logConfig = logConfig; this.logBase = logBase; } @Override public void afterPropertiesSet() { ThreadNext.start(this, "aspectLogTime"); } private void initToday() { String today = DateHelper.getToday(); if (!StringHelper.compare(this.today, today)) { synchronized (this.todayMemoryCache) { this.next(); if (!StringHelper.compare(this.today, today)) { this.todayMemoryCache.clear(); this.today = today; } } } } /** * 获取缓存对象 * * @param tag 标签 * @param urlFrom 地址 * @param level 等级 * @return 缓存对象 */ private LogUrlCountVo getCount(String tag, String urlFrom, int level) { // 初始化日期 initToday(); // 关键字 String key = StringHelper.getId(tag, urlFrom, level); // 缓存中获取对象 LogUrlCountVo ret = todayMemoryCache.get(key); if (ret != null) { return ret; } // 缓存中不存在则创建对象 synchronized (todayMemoryCache) { ret = todayMemoryCache.get(key); if (ret != null) { return ret; } ret = new LogUrlCountVo(tag, urlFrom, level); todayMemoryCache.put(key, ret); return ret; } } /** * 结束 * * @param log 日志信息 */ public void finish(LogInfoVo log) { if (log == null) { return; } // 设置当前等级 LogInfoVo.Handle handle = new LogInfoVo.Handle(log.getLevel(), log.getUseTime(), log.getStatus() == LogInfoVo.STATUS_ERROR); synchronized (log) { // 非第一次处理 LogInfoVo.Handle hisHandle = log.getHandle(); if (hisHandle != null) { // 当前合计对象 LogUrlCountVo count = getCount(log.getTag(), log.getUrl(), hisHandle.getLevel()); count.subFinish(hisHandle.getUseTime(), hisHandle.isLog()); } log.setHandle(handle); // 当前合计对象 LogUrlCountVo count = getCount(log.getTag(), log.getUrl(), handle.getLevel()); count.addFinish(handle.getUseTime(), handle.isLog()); } } @Override public boolean next() { LogCountResult todayResult = new LogCountResult(this.today, todayMemoryCache.getValues()); List list = todayResult.getList(); if (list.isEmpty()) { return true; } // 先按照等级排序,然后再按照使用总时间升序排序 list.sort(Comparator.comparing(LogUrlCountVo::getLevel) .thenComparing(LogUrlCountVo::getTotalTime)); // 逆转排序 Collections.reverse(list); // 今日合计 logBase.notifyTodayCount(todayResult); // 下次继续执行 return true; } @Override public int getNextTime() { return logConfig.getLogCountTime(); } }