@Aspect
@Order(5)
@Component
@Slf4j
public class ControllerLogAspect {
private final ThreadLocal<Long> STARTTIME_THREADLOCAL = new NamedThreadLocal<Long>("ThreadLocalStartTime");
@Pointcut("execution(public * com.xxx.controller..*.*(..))")
public void controllerLog() {
}
@Before("controllerLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 开始时间(该数据只有当前请求的线程可见)
STARTTIME_THREADLOCAL.set(System.currentTimeMillis());
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 只记录post方法
if("POST".equals(request.getMethod())){
// 记录下请求内容
log.info("********************************************");
log.info("请求URL : " + request.getRequestURL());
log.info("客户端ip ["+ request.getRemoteAddr() +"]");
log.info("请求映射 : 【" + joinPoint.getSignature().getDeclaringTypeName() + "】类的【" + joinPoint.getSignature().getName() + "】方法");
// 获取参数, 只取自定义的参数, 自带的HttpServletRequest, HttpServletResponse不管
if (joinPoint.getArgs().length > 0) {
for (Object o : joinPoint.getArgs()) {
if (Objects.isNull(o) || o instanceof MultipartFile || o instanceof MultipartFile[] || o instanceof HttpServletRequest || o instanceof HttpServletResponse) {
continue;
}
log.info("请求参数 : " + JSONObject.toJSONString(o));
}
}
}
// 只记录post方法
if("GET".equals(request.getMethod())){
// 记录下请求内容
log.info("请求URL : " + request.getRequestURL());
log.info("请求IP : " + request.getRemoteAddr());
log.info("请求映射 : 【" + joinPoint.getSignature().getDeclaringTypeName() + "】类的【" + joinPoint.getSignature().getName() + "】方法");
// 获取参数, 只取自定义的参数, 自带的HttpServletRequest, HttpServletResponse不管
if (joinPoint.getArgs().length > 0) {
for (Object o : joinPoint.getArgs()) {
if (Objects.isNull(o) || o instanceof MultipartFile || o instanceof MultipartFile[] || o instanceof HttpServletRequest || o instanceof HttpServletResponse) {
continue;
}
log.info("请求参数 : " + JSONObject.toJSONString(o));
}
}
}
}
@AfterReturning(returning = "ret", pointcut = "controllerLog()")
public void doAfterReturning(Object ret) throws Throwable {
final Long startTime = STARTTIME_THREADLOCAL.get();
final Long endTime = System.currentTimeMillis();
String message = "开始时间: {}; 结束时间: {}; 耗时: {}s; 返回: {}; ";
// 处理完请求,返回内容
log.info(message, DateUtil.format(startTime, "HH:mm:ss.SSS"), DateUtil.format(endTime, "HH:mm:ss.SSS"),
String.valueOf((endTime - startTime) / 1000.00), JSONObject.toJSONString(ret));
}
}