使用切面记录请求参数与返回结果
因为在上月底有一次大的版本上线,而因为前期测试不足导致上线后系统不太稳定,所以才打算把这块补上。。。
@Aspect
@Component
@Order(1) //执行顺序排前
public class RequestLogHandle {
//标定好切点位置
@Pointcut(value = "execution(* com.test.apicode.*.controller.*.*(..))")
public void action() {
}
@Around(value = "action()")
public Object around(ProceedingJoinPoint point) throws Throwable {
// 获取当前登录的httpServeletRequest 对象
HttpServletRequest request = HttpServletUtil.getHttpServletRequest();
String uri = request.getRequestURI();
if (StringUtils.isEmpty(uri)) {
return point.proceed();
}
//打印请求日志,利于查询问题
LinkedHashMap<String, String> mapLog = new LinkedHashMap<>();
mapLog.put("url", request.getRequestURL().toString());
mapLog.put("HTTP Method", request.getMethod());
mapLog.put("Class Method", point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());
mapLog.put("IP", request.getRemoteAddr());
Object[] args = point.getArgs();
Object[] arguments = new Object[args.length];
for (int i = 0; i < args.length; i++) {
// ServletRequest, ServletResponse尽量不要出现在参数中
//MultipartFile文件上传可以使用阿里云的OSS产品,实在不行就过滤
if (args[i] instanceof ServletRequest
|| args[i] instanceof ServletResponse
|| args[i] instanceof MultipartFile) {
Log.info(this,"这个地址参数存在问题request,respoonse,file:{}",uri);
// 跳过不能序列化的参数
continue;
}
arguments[i] = args[i];
}
String paramter = "";
if (arguments != null) {
try {
paramter = JSONObject.toJSONString(arguments);
} catch (Exception e) {
paramter = arguments.toString();
}
}
boolean showArgs = Boolean.TRUE;
if (StringUtils.isBlank(paramter)) {
showArgs = Boolean.FALSE;
}
// 打印请求入参
if (showArgs) {
mapLog.put("Request Args", paramter);
} else {
mapLog.put("Request Args", "args is null");
}
Log.info(this, "{}", JSONObject.toJSONString(mapLog));
return point.proceed();
}
/**
* 后置通知
*
* @param point
* @param rvt 返回值(和returning指定的名字一样)
*/
@AfterReturning(value = "action()", returning = "rvt")
public void afterMethod(JoinPoint point, Object rvt) {
MethodSignature sig = (MethodSignature) point.getSignature();
Method method = sig.getMethod();
if (null != rvt && null != method.getDeclaringClass()) {
try {
Log.info(this, "{}.{} : 返回数据:{}", method.getDeclaringClass().getName(), method.getName(), JSONObject.toJSONString(rvt));
} catch (Exception e) {
Log.info(this, e.getMessage());
}
}
}
}