在实际的项目开发过程,通过记录日志,可以帮助我们快速定位的排查问题可能出现bug
的地方,根据打印请求参数requestParams
或者处理后返回的结果responeBody
等信息,清楚接口的执行情况。
本文以aop自定义注解的方式实现
一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
二、自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD})
@Documented
public @interface LogInfo {
//描述
String value() default "";
}
三、定义打印日志的切面类
package com.he.aop;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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;
/**
* 作者: wangzai
* 时间: 2021/12/10 23:55
* 描述:
*/
@Aspect
@Slf4j
@Component
public class LogAspect {
//切点
@Pointcut("@annotation(com.he.aop.LogInfo)")
public void PointCut(){
}
//环绕通知
@Around("LogAspect.PointCut()")
public Object methodLogAround(ProceedingJoinPoint joinPoint) throws Throwable{
Object obj;
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
Method method = signature.getMethod();
// 获取类名
String className = method.getDeclaringClass().getName();
// 获取方法名
String methodName = method.getName();
// 获取参数值
Object[] args = joinPoint.getArgs();
log.info("com.he.aop.LogAspect#methodLogAround execute start, method = {},requestParams ={}",className+"."+methodName,
args != null ? JSON.toJSONString(args): StringUtils.EMPTY);
try {
obj = joinPoint.proceed(args);
}catch (Exception e){
log.error("com.he.aop.LogAspect#methodLogAround execute error, method = {},requestParams ={}",className+"."+methodName,
e.getMessage());
throw e;
}
log.info("com.he.LogAspect#methodLogAround execute end, method = {},resultBody= {}",className+"."+methodName,
obj != null ? JSON.toJSONString(obj): StringUtils.EMPTY);
return obj;
}
}
三、测试验证
请求url地址参数:
http://localhost:8082/user/page?currentPage=1&pageSize=2
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@GetMapping("/page")
@LogInfo("log....")
public Object pageQuery(@RequestParam(required = false,defaultValue = "1") Integer currentPage,
@RequestParam(required = false,defaultValue = "10") Integer pageSize){
List<UserDTO> page = userService.page(currentPage, pageSize);
return page;
}
}
打印结果
个人学习总结,如写的有不足的地方,可在评论区指出