import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.***.****.common.ResponseBean;
@Aspect
@Component
public class LoggerInterceptor {
private static final Logger log = LoggerFactory.getLogger(LoggerInterceptor.class);
@Around("execution(* com.xxx..*..*.*Controller.*(..))")
public Object doAroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
ObjectMapper obj = (new ObjectMapper()).disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
StringBuffer method = new StringBuffer();
method.append(joinPoint.getTarget().getClass().getSimpleName()).append(".");
method.append(joinPoint.getSignature().getName()).append("#");
StringBuffer buffer = new StringBuffer();
buffer.append(method);
Object[] arguments = joinPoint.getArgs();
Object[] result = arguments;
int arg6 = arguments.length;
for (int arg7 = 0; arg7 < arg6; ++arg7) {
Object arg = result[arg7];
if (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)
&& !(arg instanceof MultipartFile) && !(arg instanceof MultipartFile[])) {
buffer.append(obj.writeValueAsString(arg));
}
}
log.info("request#{}", buffer.toString());
Object arg9 = joinPoint.proceed();
String resultMessage = getResultMessage(obj,arg9);
log.info("resultMessage#{}", resultMessage);
return arg9;
}
private String getResultMessage(ObjectMapper obj, Object result) {
String resultStr = null;
try {
if (result instanceof ResponseBean) {
resultStr = obj.writeValueAsString(result);
return resultStr;
} else {
return obj.writeValueAsString(result);
}
} catch (Exception arg4) {
return "";
}
}
}
SpringBoot AOP实现拦截接口请求与响应结果
于 2023-08-09 15:36:20 首次发布