1.AOP拦截器:
package com.longjin.comm.utils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static java.util.stream.Collectors.joining;
/**
* @Description:AOP拦截打印请求地址、参数
* @Author 何志鹏
* @Date 2020/6/1 14:30
* @Version 1.0
*/
@Aspect
@Component
@Slf4j
public class ConsoleLogAspect {
//设置切面点
@Pointcut(value = "(execution(* com.longjin.wechat.controller.*.*(..)) || execution(* com.longjin.admin.system.controller.*.*(..)))")
public void webLog() {}
//指定切点前的处理方法
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Exception {
//获取request对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
StringBuilder sb = new StringBuilder();
//拼接请求内容
sb.append("\n请求路径:" + request.getRequestURL().toString() + " " + request.getMethod() + "\n");
//判断请求是什么请求
if (request.getMethod().equalsIgnoreCase(RequestMethod.GET.name())) {
Map<String, String[]> parameterMap = request.getParameterMap();
Map<String, String> paramMap = new HashMap<>();
parameterMap.forEach((key, value) -> paramMap.put(key, Arrays.stream(value).collect(joining(","))));
sb.append("请求参数:" + JSON.toJSONString(paramMap));
} else if (request.getMethod().equalsIgnoreCase(RequestMethod.POST.name())) {
Object[] args = joinPoint.getArgs();
StringBuilder stringBuilder = new StringBuilder();
Arrays.stream(args).forEach(object -> stringBuilder.append(object.toString().replace("=",":")));
if (stringBuilder.length() == 0){
stringBuilder.append("{}");
}
sb.append("请求参数:" + stringBuilder.toString());
}
log.info(sb.toString());
}
//指定切点前的处理方法
@AfterReturning(pointcut = "webLog()",returning = "result")
public void doAfterReturning(Object result) {
if (ObjectUtils.isEmpty(result)){
return;
}
log.info("\n返回結果:" + JSON.toJSONString(result));
}
}
2.日志打印控制台效果如下: