打印接口请求信息切面,方便开发调试
根据项目环境自己实现下toStr方法
import org.aspectj.lang.JoinPoint;
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.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* 接口请求信息切面,方便开发调试
*
* @author Alone
*/
@Aspect
@Order(-77)
@Component
// 非生产环境启用
@ConditionalOnExpression("'${spring.profiles.active}' != 'prod'")
public class RequestInfoAspect {
private static final Logger log = LoggerFactory.getLogger(RequestInfoAspect.class);
@Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
public void restController() {
}
@Pointcut("@within(org.springframework.stereotype.Controller)")
public void controller() {
}
@Around("restController() || controller()")
public Object beforeReq(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取请求对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return joinPoint.proceed();
}
HttpServletRequest request = attributes.getRequest();
//获取请求者IP
String ip = IpUtil.getIpAddr(request);
boolean innerIp = IpUtil.isInnerIp(ip);
//获取请求的parameter
String param = toStr(request.getParameterMap());
//获取Body
String body = getRequestBody(joinPoint, request);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object result = null;
try {
result = joinPoint.proceed();
return result;
} finally {
stopWatch.stop();
log.info("\n╔═════════════════访问接口═════════════════╗\n" +
"║请求IP:{},{}\n" +
"║请求方式:{}\n" +
"║请求接口:{}\n" +
"║请求参数:{}\n" +
"║请求体:{}\n" +
"║返回数据:{}\n" +
"║耗时(毫秒):{}\n" +
"╚═════════════════════════════════════════╝\n",
innerIp ? "内网" : "外网",
ip,
request.getMethod(),
request.getRequestURI(),
param,
((body.length() >= 300) ? body.substring(0, 300) + " ..." : body),
result != null
? (result.toString().length() < 200
? result
: result.toString().substring(0, 198))
: ("{}"),
stopWatch.getTotalTimeMillis());
}
}
private String getRequestBody(JoinPoint joinPoint, HttpServletRequest request) {
Object requestBody = null;
if (HttpMethod.POST.name().equals(request.getMethod())
|| HttpMethod.PUT.name().equals(request.getMethod())) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Object[] params = joinPoint.getArgs();
Annotation[][] annotations = method.getParameterAnnotations();
for (int i = 0; i < annotations.length; i++) {
Object param = params[i];
Annotation[] paramAnn = annotations[i];
if (param == null || paramAnn.length == 0) {
continue;
}
for (Annotation annotation : paramAnn) {
if (annotation.annotationType().equals(RequestBody.class)) {
requestBody = param;
}
}
}
}
return requestBody != null
? toStr(requestBody)
: "";
}
/**
* TODO 自定转换实现, 用项目自带json工具之类的转换
*
* @param data data
* @return String
*/
private String toStr(Object data) {
return data.toString();
}
}
class IpUtil {
public static String getIpAddr(HttpServletRequest request) {
String ipAddress;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if ("127.0.0.1".equals(ipAddress)) {
// 根据网卡取本机配置的IP
try {
InetAddress inet = InetAddress.getLocalHost();
ipAddress = inet.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
// "***.***.***.***".length()
if (ipAddress != null && ipAddress.length() > 15) {
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress = "";
}
return ipAddress;
}
public static boolean isInnerIp(String ipAddress) {
long ipNum = getIpNum(ipAddress);
/*
私有IP:A类 10.0.0.0-10.255.255.255
B类 172.16.0.0-172.31.255.255
C类 192.168.0.0-192.168.255.255
当然,还有127这个网段是环回地址
**/
long aBegin = getIpNum("10.0.0.0");
long aEnd = getIpNum("10.255.255.255");
long bBegin = getIpNum("172.16.0.0");
long bEnd = getIpNum("172.31.255.255");
long cBegin = getIpNum("192.168.0.0");
long cEnd = getIpNum("192.168.255.255");
return isInner(ipNum, aBegin, aEnd)
|| isInner(ipNum, bBegin, bEnd)
|| isInner(ipNum, cBegin, cEnd)
|| "127.0.0.1".equals(ipAddress)
|| "127.0.1.1".equals(ipAddress);
}
private static long getIpNum(String ipAddress) {
String[] ip = ipAddress.split("\\.");
long a = Integer.parseInt(ip[0]);
long b = Integer.parseInt(ip[1]);
long c = Integer.parseInt(ip[2]);
long d = Integer.parseInt(ip[3]);
return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
}
private static boolean isInner(long userIp, long begin, long end) {
return (userIp >= begin) && (userIp <= end);
}
}