SpringBoot 拦截请求打印日志
java
import lombok.extern.slf4j.Slf4j;
import cn.hutool.json.JSONUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Slf4j
@Aspect
@Component
public class BusDealConf {
@Around("@within(org.springframework.web.bind.annotation.RestController)" +
"||@within(org.springframework.stereotype.Controller)")
public Object around(ProceedingJoinPoint point) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
log.info("----------------------------------------开始----------------------------------------");
if (null != attributes) {
HttpServletRequest request = attributes.getRequest();
log.info("请求路径: {}", request.getRequestURI());
log.info("请求方式: {}", request.getMethod());
log.info("请求方法: {}", point.getSignature());
log.info("请求参数: {}", JSONUtil.toJsonPrettyStr(getPara(point.getArgs())));
}
long t1 = System.currentTimeMillis();
Object result = point.proceed(point.getArgs());
long t2 = System.currentTimeMillis();
//log.info("响应参数: {}", JSONUtil.toJsonPrettyStr(result));
log.info("执行耗时: {}ms", t2 - t1);
log.info("----------------------------------------结束----------------------------------------");
return result;
}
private List<Object> getPara(Object[] objects) {
return Arrays.stream(objects)
.filter(obj -> !(obj instanceof MultipartFile)
&& !(obj instanceof HttpServletResponse)
&& !(obj instanceof HttpServletRequest)).collect(Collectors.toList());
}
}