Spring AOP+自定义注解实现日志记录

利用spring aop+自定义注解,来实现日志的记录,把日志记录从业务中解放出来,你只需专注于你的业务代码实现,保持业务代码的干净。自定义日志注解,释放你的双手。

日志类注解ClassLogger:

import java.lang.annotation.*;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ClassLogger {
}

日志方法注解MethodLogger:

import java.lang.annotation.*;

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

}

定义切入点LogAdvice,记录日志:

@Service
@Aspect
public class LogAdvice {

    private static final Logger logger = LoggerFactory.getLogger(LogAdvice.class);
    private final int maxLength = 2000;

    @Pointcut("@within(com.chengbinbbs.membercenter.log.ClassLogger)")
    public void classLog(){}

    @Pointcut("@annotation(com.chengbinbbs.membercenter.log.MethodLogger)")
    public  void methodLog() {
    }

    @Around(value = "classLog() || methodLog() " )
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        final long begin = System.currentTimeMillis();
        String args = JsonUtil.Obj2Str(pjp.getArgs());
        if (null != args && args.length() > this.maxLength) {
            args = args.substring(0, this.maxLength);
        }

        Object returnObj = null;
        try {
            returnObj = pjp.proceed();
        } catch (final Throwable throwable) {
            logger.error("[LogAdvice.doAround] throwable=", throwable);
            throw throwable;
        } finally {
            String returnStr = JsonUtil.Obj2Str(returnObj);
            if (null != returnStr && returnStr.length() > this.maxLength) {
                returnStr = returnStr.substring(0, this.maxLength);
            }
            long timeUsed = System.currentTimeMillis() - begin;
            this.logger.info("LogAdvice|{}|method:{}|cost:{}ms|args:{}|return:{}",
                    (timeUsed > 300 ? "TimeOut":"") , pjp.toLongString(),timeUsed,
                    args, returnStr);
        }
        return returnObj;
    }
}

简单使用:

@Service
@ClassLogger
public class MallUserServiceImpl implements MallUserService {

    private MallUserBiz mallUserBiz;

    @Autowired
    public MallUserServiceImpl(MallUserBiz mallUserBiz) {
        this.mallUserBiz = mallUserBiz;
    }
    @MethodLogger
    public CallResultDTO helloWorld(Long userId) {
        return null;
    }
  }

猜你喜欢

转载自blog.csdn.net/chengbinbbs/article/details/80882307