在Restapi这层放置一个拦截器,在日志中打印出入参的参数名和参数值:
这个主要是注意ServletRequest和ServletResponse 不能就行序列化。
package com.*.*.*.restapi.aspect;
import com.alibaba.fastjson.JSONObject;
import com.*.common.util.GSONUtil;
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.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.lang.reflect.Method;
/**
* 日志拦截器
* Created by yang
*/
@Aspect
@Component
public class ControllerLogAspect {
private static final Logger logger = LoggerFactory.getLogger(ControllerLogAspect.class);
@Pointcut("execution(* com.*.*.*.restapi.web..*.*(..))")
public void controllerLog(){}
@Around("controllerLog()")
public Object around(ProceedingJoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
Object[] arguments = new Object[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
//ServletRequest不能序列化,从入参里排除,否则报异常:java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
//ServletResponse不能序列化 从入参里排除,否则报异常:java.lang.IllegalStateException: getOutputStream() has already been called for this response
continue;
}
arguments[i] = args[i];
}
String paramter = "";
if (arguments != null) {
try {
paramter = JSONObject.toJSONString(arguments);
} catch (Exception e) {
paramter = arguments.toString();
}
}
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
String[] parameterNames = signature.getParameterNames();
logger.info("开始调用--> {}的{}方法,参数名称:{}参数值:{}", method.getDeclaringClass().getSimpleName(), method.getName(), JSONObject.toJSONString(parameterNames), paramter);
try {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
logger.info("调用结束--> {}的{}方法,返回值:{},耗时:{}ms", method.getDeclaringClass().getSimpleName(), method.getName(), JSONObject.toJSONString(result), String.valueOf(System.currentTimeMillis() - start));
return result;
} catch (Throwable throwable) {
logger.error(throwable.getMessage(), throwable);
}
return null;
}
}