添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
定义日志注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MethodLog {
}
定义日志切面
@Aspect
@Component
public class MethodLogAspect {
@Pointcut("@annotation(com.example.demo.common.log.MethodLog)")
public void log() {
}
/**
* 加入注解自动记录方法日志
*
* @param joinPoint
* @return
* @throws Throwable
*/
@Around(value = "log()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取执行方法的类的名称(包名加类名)
String className = joinPoint.getTarget().getClass().getName();
// 获取实例和方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Logger log = LoggerFactory.getLogger(className);
Object[] args = joinPoint.getArgs();
// 记录日志
log.info(className + "#" + method.getName() + " start..., params:{}", JSON.toJSONString(args));
long startTime = System.currentTimeMillis();
// 执行方法获取返回值
Object proceed = joinPoint.proceed();
long end = System.currentTimeMillis();
// 记录日志
log.info(className + "#" + method.getName() + " end, execute time: [{}], return: {}", end - startTime, JSON.toJSONString(proceed));
// 返回
return proceed;
}
}
使用
@MethodLog
@RequestMapping(method = RequestMethod.POST)
public ReturnResult<String> login(@RequestBody User validUser) throws BizException {
结果