通过AOP实现日志打印,可以减少代码量以及提高代码可读性、记录方法的执行时间,方便后续程序的优化、方便发现问题和定位问题。
1、使用方式
@GetMapping("/test")
@AutoLog(value = "修改订单收货地址", type = 1)
public CommonResult<String> test(){
return CommonResult.success("操作成功");
}
2、自定义注解类
import java.lang.annotation.*;
/**
* 日志打印注解
* @date 2023/5/23 16:10
* @author luohao
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AutoLog {
/**
* 日志内容
* @return
*/
String value() default "";
/**
* 1、打印入参和出参;2、打印入参;3、打印出参
* @return
*/
int type() default 1;
}
3、切面实现日志打印类
import com.alibaba.fastjson.JSONObject;
import com.scm.boss.common.annotation.AutoLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* 日志打印
* @date 2023/5/23 16:07
* @author luohao
*/
@Slf4j
@Aspect
@Component
public class SpendTimeAspect {
@Pointcut("@annotation(com.scm.boss.common.annotation.AutoLog)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
AutoLog syslog = method.getAnnotation(AutoLog.class);
Long startTime = System.currentTimeMillis();
String strClassName = point.getTarget().getClass().getName();
String strMethodName = point.getSignature().getName();
int type = syslog.type();
Object[] args = point.getArgs();
Object obj = null;
try {
obj = point.proceed();
return obj;
} finally {
Long endTime = System.currentTimeMillis();
if(type == 2) {
log.info("[类名]:{},[方法]:{},[接口名称]:{},耗时:{},入参:{}", strClassName, strMethodName, syslog.value(), endTime - startTime, JSONObject.toJSONString(args));
}else if(type == 3) {
log.info("[类名]:{},[方法]:{},[接口名称]:{},耗时:{},出参:{}", strClassName, strMethodName, syslog.value(), endTime - startTime, JSONObject.toJSONString(obj));
}else {
log.info("[类名]:{},[方法]:{},[接口名称]:{},耗时:{},入参:{},出参:{}", strClassName, strMethodName, syslog.value(), endTime - startTime, JSONObject.toJSONString(args), JSONObject.toJSONString(obj));
}
}
}
}