SpringBoot项⽬⽇志打印请求参数及返回参数SpringBoot项⽬优雅⽇志打印请求参数及返回参数
SpringBoot项⽬优雅⽇志打印请求参数及返回参数:
需求:1:请求参数及响应内容⽇志打印交给切⾯进⾏管理,避免⼿动创建log对象进⾏⽇志记录打印
2:基于注解的Controller的Method,添加注解进⾏打印,不添加注解不打印⽇志,便于根据实际情况⽇志的输出.实现如下
添加依赖:
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
springboot aop创建⾃定义注解:
import*;
@Retention(RetentionPolicy.RUNTIME)//注解不仅被保存到class⽂件中,jvm加载class⽂件之后,仍存在
@Target(ElementType.METHOD)//注解添加的位置
@Documented
public@interface LogPrint {
String description()default"";
}
写⼀个切⾯类进⾏⽇志输出管理:
package**.config.aspect;
import JSONObject;
import LogPrint;
import Slf4j;
import JoinPoint;
import ProceedingJoinPoint;
import*;
import Profile;
import Component;
import RequestContextHolder;
import ServletRequestAttributes;
import MultipartFile;
import HttpServletRequest;
import HttpServletResponse;
import Method;
@Aspect
@Component
@Profile({"dev","test"})//⼀般⽣产环境不允许⽇志打印参数
@Slf4j
public class LogPrintAspect {
/** 换⾏符 */
private static final String LINE_SEPARATOR = System.lineSeparator();
/** 以⾃定义 @LogPrint 注解为切点 */
// 这个地⽅换成⾃⼰的包路径
@Pointcut("@annotation(com.*.*.config.annotation.LogPrint)")
public void logPrint(){}
/**
* 在切点之前织⼊
* @param joinPoint
* @throws Throwable
*/
@Before("logPrint()")
public void doBefore(JoinPoint joinPoint)throws Throwable {
// 开始打印请求⽇志
ServletRequestAttributes attributes =(ServletRequestAttributes) RequestAttributes();
HttpServletRequest request = Request();
// 获取 @WebLog 注解的描述信息
String methodDescription =getAspectLogDescription(joinPoint);
// 打印请求相关参数
log.info("========================================== Start ==========================================");
// 打印请求 url
log.info("URL            : {}", RequestURL().toString());
// 打印描述信息
log.info("Description    : {}", methodDescription);
// 打印 Http method
log.info("HTTP Method    : {}", Method());
// 打印调⽤ controller 的全路径以及执⾏⽅法
log.info("Class Method  : {}.{}", Signature().getDeclaringTypeName(), Signature().getName());
// 打印请求的 IP
log.info("IP            : {}", RemoteAddr());
// 打印请求⼊参
log.info("Request Args  : {}",getParams(joinPoint));
}
/**
* 在切点之后织⼊
* @throws Throwable
*/
@After("logPrint()")
public void doAfter()throws Throwable {
// 接⼝结束后换⾏,⽅便分割查看
log.info("=========================================== End ==========================================="+ LINE_SEPARATOR); }
/**
* 环绕
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("logPrint()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint)throws Throwable {
long startTime = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed();
// 打印出参
log.info("Response Args  : {}",  JSONString(result));
// 执⾏耗时
log.info("Time-Consuming : {} ms", System.currentTimeMillis()- startTime);
return result;
}
/**
/**
* 获取切⾯注解的描述
*
* @param joinPoint 切点
* @return 描述信息
* @throws Exception
*/
public String getAspectLogDescription(JoinPoint joinPoint)
throws Exception {
String targetName = Target().getClass().getName();
String methodName = Signature().getName();
Object[] arguments = Args();
Class targetClass = Class.forName(targetName);
Method[] methods = Methods();
StringBuilder description =new StringBuilder("");
for(Method method : methods){
Name().equals(methodName)){
Class[] clazzs = ParameterTypes();
if(clazzs.length == arguments.length){
description.Annotation(LogPrint.class).description());
break;
}
}
}
String();
}
private String getParams(JoinPoint joinPoint){
String params ="";
Args()!=null&& Args().length >0){
for(int i =0; i < Args().length; i++){
Object arg = Args()[i];
if((arg instanceof HttpServletResponse)||(arg instanceof HttpServletRequest) ||(arg instanceof MultipartFile)||(arg instanceof MultipartFile[])){
continue;
}
try{
params +=Args()[i]);
}catch(Exception e1){
<(e1.getMessage());
}
}
}
return params;
}
}
效果如下:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。