自定义实现日志注解
手动代码开始!
创建自定义日志注解@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作用在对应的接口上即可
本文介绍了如何创建并使用自定义的日志注解@AutoLog,结合AOP(面向切面编程)实现在方法执行前后记录日志。在注解中定义了value属性,通过获取注解值并在切点执行前后打印相关信息,实现对方法调用的跟踪。此技术可以用于记录系统操作日志,方便后期排查问题。
216

被折叠的 条评论
为什么被折叠?



