在springboot项目中使用的切面aop,打印各个请求的请求参数和相应参数。
注意:post请求和get请求获取参数的方式不同。request.getQueryString();使用与get请求
import com.fasterxml.jackson.databind.ObjectMapper;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
//描述切面类
@Aspect
@Configuration
@Component
public class HttpControllerAop {
private static final Logger logger = LoggerFactory.getLogger(HttpControllerAop.class);
/**
* 定义切点Pointcut
*/
@Pointcut("execution(* com.hfy..*HttpController.*(..))")
public void excudeService() {
}
@Around("excudeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
ObjectMapper mapper = new ObjectMapper();
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
String uri = request.getRequestURI();
String queryString = request.getQueryString();
Map<String, String[]> params = request.getParameterMap();
if (params != null) {
queryString = mapper.writeValueAsString(params);
}
String method = request.getMethod();
if ("POST".equals(method)) {
Object[] paramsArray = pjp.getArgs();
if (paramsArray.length > 0) {
queryString = mapper.writeValueAsString(paramsArray[0]);
}
} else {
queryString = request.getQueryString();
}
logger.info("请求uri: ({}), params: {}", uri, queryString);
// result的值就是被拦截方法的返回值
Object result = pjp.proceed();
// 过滤 高频或数据量大的日志,不打印
return result;
}
}