package com.yanzuoguang.log; import com.yanzuoguang.util.exception.ExceptionHelper; import com.yanzuoguang.util.thread.ThreadNext; import com.yanzuoguang.util.vo.CloudConfig; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import java.util.List; import java.util.Optional; import java.util.concurrent.LinkedBlockingQueue; /** * 获取当前日志对象 * * @author 颜佐光 */ @Component public class LogBase implements ThreadNext.Next, InitializingBean { /** * 缓存队列 */ protected volatile LinkedBlockingQueue<LogInfoVo> cache = new LinkedBlockingQueue<>(); private final CloudConfig cloudConfig; private final LogFeignBase logFeign; public LogBase(CloudConfig cloudConfig, LogFeignDefault logFeignDefault, Optional<LogFeign> logFeign) { this.cloudConfig = cloudConfig; if (logFeign.isPresent()) { this.logFeign = logFeign.get(); } else { this.logFeign = logFeignDefault; System.err.println("请添加处理日志服务,实现LogFeign接口!"); } } /** * Invoked by a BeanFactory after it has set all bean properties supplied * (and satisfied BeanFactoryAware and ApplicationContextAware). * <p>This method allows the bean instance to perform initialization only * possible when all bean properties have been set and to throw an * exception in the event of misconfiguration. * * @throws Exception in the event of misconfiguration (such * as failure to set an essential property) or if initialization fails. */ @Override public void afterPropertiesSet() throws Exception { // 判断是否要记录日志 if (cloudConfig.isLogBase()) { ThreadNext.start(this, "save log error"); } } /** * 添加日志到缓存中,并不是立即添加,而是通过线程执行,防止对环境造成影响 * * @param logVo 日志信息 */ public void addLog(LogInfoVo logVo) { // 当不记录日志时,则直接忽略 if (!cloudConfig.isLogBase()) { return; } cache.add(logVo); } public void notifyNotHandle(List<LogInfoVo> notHandles) { logFeign.notifyNotHandle(notHandles); } public void notifyTodayCount(LogCountResult todayResult) { logFeign.notifyTodayCount(todayResult); } /** * 执行下一个函数,出现异常会继续执行 * * @return 是否继续执行 */ @Override public boolean next() { if (cache.isEmpty()) { return true; } // 循环处理日志信息 while (!cache.isEmpty()) { // 取出一条日志 LogInfoVo item = cache.poll(); // 判断日志信息是否为空 if (item == null) { continue; } // 保存日志 try { logFeign.save(item); } catch (Exception ex) { ExceptionHelper.PrintError(LogBase.class, ex); } } return true; } /** * 沉睡时间 * * @return 下次执行时间 */ @Override public int getNextTime() { return 100; } }