package top.mytao.myproject.platform.aspact;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.mytao.myproject.platform.domain.Result;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
* @Description:
* @Author: caomt
* @Date Create In 14:42 2019/1/11
* @Modified By:
*/
@Aspect
@Component
public class WebLogAspect {
private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
@Pointcut("execution(public * top.mytao.myproject.platform.controller.BaseController+.*(..))")
public void webLog() {
}
/**
* 前置拦截请求参数信息
*
* @param joinPoint
* @throws Throwable
*/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Exception {
//获取目标方法的参数信息
Signature signature = joinPoint.getSignature();
// 接收到请求,记录请求内容 记录
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String HTTP_METHOD = request.getMethod();
// 请求地址
logger.info("URL : " + request.getRequestURL().toString());
// 请求方法
logger.info("HTTP_METHOD : " + HTTP_METHOD);
/*
请求ip地址
如果通过ningx 代理,获取真实的ip地址,
如果 request.getHeader("X-Real-IP") 不存在 则通过request.getRemoteAddr()获取ip地址
*/
String realIp = request.getHeader("X-Real-IP");
if (realIp != null) {
logger.info("IP : " + realIp);
} else {
logger.info("IP : " + request.getRemoteAddr());
}
if ("GET".equals(HTTP_METHOD)) {
Enumeration<String> enu = request.getParameterNames();
StringBuilder params = new StringBuilder();
params.append("RequestParam : ");
while (enu.hasMoreElements()) {
String name = enu.nextElement();
// 请求参数
params.append(name).append(" =").append(request.getParameter(name)).append(", ");
}
logger.info(params.toString());
} else {
// 获取参数信息
logger.info("RequestParam : " + JSONObject.toJSONString(joinPoint.getArgs()));
}
// AOP代理类的名字和方法
logger.info("PACKAGE : " + signature.getDeclaringTypeName() + "+" + signature.getName());
}
/**
* 后置通知
*
* @param ret
* @throws Throwable
*/
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
if (ret instanceof Result) {
Result res = (Result) ret;
logger.info("Result : (code =" + res.getCode() + ", msg =" + res.getMessage() + ")");
}
}
}
网友评论