自定义实现日志注解
手动代码开始!
创建自定义日志注解@AutoLog
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface AutoLog {
String value()
}
AOP实现注解想要的功能
@Slf4j
@Component
@Aspect
public class AutoLogAspect {
@Autowired
private HttpServletRequest request;
@Pointcut("@annotation(com.yck.common.annotation.AutoLog)")
public void pointCut(){
}
// 在切点运行前执行
@Before(value = "pointCut()")
public void doBefore(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
Method method = signature.getMethod();
AutoLog annotation = method.getAnnotation(AutoLog.class);
if (null == annotation) return;
// TODO 将日志写入数据库
// 注解的value值
// annotation.value();
// 测试打印
String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
log.info("start:{},method:{},url:{}", methodName, annotation.value(), request.getRequestURI());
}
// 在切点运行后,无异常时执行
@AfterReturning(value = "pointCut()", returning = "result")
public void afterReturn(JoinPoint joinPoint, Object result) {
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
Method method = signature.getMethod();
AutoLog annotation = method.getAnnotation(AutoLog.class);
if (null == annotation) return;
// 测试打印
String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
log.info("end:{},result:{}", methodName, result);
}
}
@AutoLog作用在对应的接口上即可