java-动态注解日志

定义注解

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {

    String value() default "";

    ServiceSysLogEnum sysLogEnum();
}

日志注解调用实现类 

@Slf4j
@Lazy
@Aspect
@Component
public class ServiceSysLogImpl implements Ordered {

    @Resource
    private SysLogService sysLogService;

    /**
     * 系统名称
     */
    private static final String SYSTEM = "SYSTEM";

    @Override
    public int getOrder() {
        return 1;
    }

    @Around("@annotation(sysLog)")
    @SneakyThrows
    public Object around(ProceedingJoinPoint point, SysLog sysLog) {
        //获取日志信息
        SysLogTable sysLogTable = getSysLog(point,sysLog);
        Object object = null;
        try {
            object = point.proceed();
            return object;
        } finally {
            // 记录日志
            if(null != sysLogTable){
                log.info("aop save log sysLogTable = {}",JSON.toJSONString(sysLogTable));
                //此处调用日志方法 可异步记录日志
                sysLogService.saveSysLog(sysLogTable);
            }
        }
    }

    /**
     * 获取日志对象
     * @param point
     * @param sysLog
     * @return
     */
    public SysLogTable getSysLog(ProceedingJoinPoint point, SysLog sysLog){
        Object[] args = point.getArgs();
        List argumentList = Lists.newArrayList();
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof MultipartFile || args[i] instanceof HttpServletResponse || args[i] instanceof HttpServletRequest) {
                continue;
            }
            argumentList.add(args[i]);
        }
        String entityId = "";
        String data = "";
        //此处为了 记录关联表与日志表关系 
        if (argumentList.size() > 1) {
            entityId = argumentList.get(0).toString();
            data = argumentList.get(1).toString();
        } else {
            data = JSON.toJSONString(argumentList.toArray());
        }
        log.info("getSysLog entityId = {} ,data = {}",entityId,data);
        ServiceSysLogEnum sysLogEnum = sysLog.sysLogEnum();
        //自行封装日志表
        SysLogTable sysLogTable = new SysLogTable();
        return sysLogTable;
    }
} 
  

日志实现类 

 

@Slf4j
@Service
public class SysLogServiceImpl  extends ServiceImpl implements SysLogService {

    @Resource
    private SysLogMapper sysLogMapper;

    @Async("asyncServiceExecutor")
    @Override
    public void saveSysLog(SysLogTable sysLogTable){
        sysLogMapper.insert(sysLogTable);
    }
}

定义线程池 

@EnableAsync(proxyTargetClass = true)
@Configuration
public class ExecutorConfig {

    @Bean
    public Executor asyncServiceExecutor() {
       return ThreadPoolUtil.getThreadPoolExecutor();
    }
}

 

你可能感兴趣的:(spring,java,后端)