import org.aspectj.lang.JoinPoint;
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 javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
@Aspect
@Component
public class WebLogConfig {
//获取日志信息类
private static final Logger logger = LoggerFactory.getLogger(WebLogConfig.class);
@Pointcut("execution(* com.abc.controller.*.*(..))")
public void weblog(){}
@Before(value = "weblog()")
public void doBefore(JoinPoint joinPoint){
//获取请求request
ServletRequestAttributes attributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
//通过servletRequestAttributes获取request
HttpServletRequest request = attributes.getRequest();
//获取请求的相应参数
StringBuffer url = request.getRequestURL();
//写入请求的url
logger.info("URL: " + url.toString());
String method = request.getMethod();
//写入请求的方法
logger.info("REQUEST_METHOD: " + method);
Enumeration<String> params = request.getParameterNames();
//遍历请求参数
while(params.hasMoreElements()){
String name = params.nextElement();
logger.info("name{},params{}: " + name,request.getParameter(name));
}
//获取请求的ip地址
String ip = request.getRemoteAddr();
//写入请求的ip地址
logger.info("IP: " + ip);
}
@AfterReturning(pointcut = "weblog()",returning = "ret")
public void afterRet(Object ret){
//处理完请求响应内容
logger.info("RESPONSE: " + ret);
}
}