一、自定义注解
import com.demo.common.enums.ServiceLogInfoType;
import java.lang.annotation.*;
/**
* @author haha
* @ClassName ServiceLogInfo
* @Description 日志的注解
* @date 2023/6/7 20:00
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ServiceLogInfo {
/**
* 方法的描述
*/
String desc() default "";
/**
* 日志的类型
*/
ServiceLogInfoType type() default ServiceLogInfoType.DEFAULT;
}
二、日志类型枚举
import lombok.Getter;
/**
* @author haha
* @ClassName ServiceLogInfoType
* @Description 日志的类型
* @date 2023/6/7 20:05
*/
@Getter
public enum ServiceLogInfoType {
DEFAULT(0, "默认", "打印方法的入参和结果"),
PARAM_ARGS(1, "入参", "打印方法的入参"),
RESULT(2, "结果", "打印方法的结果");
Integer type;
String name;
String desc;
ServiceLogType(Integer type, String name, String desc) {
this.type = type;
this.name = name;
this.desc = desc;
}
}
三、创建切面类
import com.demo.common.annotation.ServiceLogInfo;
import com.demo.common.enums.ServiceLogInfoType;
import com.demo.common.utils.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
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;
import java.util.Objects;
/**
* @author haha
* @ClassName ServiceLogInfoAspect
* @Description 日志的切面
* @date 2023/6/7 20:05
*/
@Aspect
@Component
@Slf4j
public class ServiceLogInfoAspect {
@Pointcut("@annotation(com.demo.common.annotation.ServiceLogInfo)")
public void point() {
}
@AfterReturning(value = "point()", returning = "result")
public void afterReturn(JoinPoint joinPoint, Object result) {
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ServiceMethodLog annotation = method.getAnnotation(ServiceLogInfo.class);
if (Objects.isNull(annotation)) {
return;
}
ServiceLogType serviceLogInfoType= annotation.type();
String prefix = method.getDeclaringClass().getName() + "." + method.getName();
if (Objects.equals(serviceLogInfoType.getType(), ServiceLogInfoType.DEFAULT.getType())) {
log.info(prefix + " params is {}, result is {}", JsonUtils.toJson(joinPoint.getArgs()), JsonUtils.toJson(result));
} else if (Objects.equals(serviceLogInfoType.getType(), ServiceLogInfoType.PARAM_ARGS.getType())) {
log.info(prefix + " params is {}", JsonUtils.toJson(joinPoint.getArgs()));
} else if (Objects.equals(serviceLogInfoType.getType(), ServiceLogInfoType.RESULT.getType())) {
log.info(prefix + " result is {}", JsonUtils.toJson(result));
}
} catch (Exception e) {
log.error("ServiceLogInfoAspect.afterReturn error", e);
}
}
}
四、使用注解打印日志
@Override
@ServiceMethodLog
public Person findById(PersonDTO person) {
return new Person();
}