@Aspect
@Component
public class WebLogAspect {
private static Logger logger = org.apache.log4j.LogManager.getLogger(WebLogAspect.class.getName());
/**
* 线程局部变量,防止 在高并发情况下,方法开始和结束时间被多个线程调用使方法运行时间出错
*/
ThreadLocal<Long> startTime = new ThreadLocal<Long>();
/**
*
* webLog:(自定义切点,我的controller层的包名为com.songsir.controller). <br/>
* @author Songsir
* @Date 2018年5月19日上午9:25:10
* @since JDK 1.8
*/
@Pointcut("execution(* com.songsir.*..*Controller.*(..))")
public void webLog(){}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint){
logger.info("\r\n----------方法开始----------");
startTime.set(System.currentTimeMillis());
/**
* 接收到请求,记录请求内容
*/
ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
/**
* 获取请求的设备相关信息
*/
String userAgent = request.getHeader("User-Agent");
/**
* 获取cookie
*/
Cookie cookies [] = request.getCookies();
String cookieInfo = getCookieInfo(cookies);
String ip = getClientIpAddress(request);
/**
* 记录下请求内容
*/
logger.info("User-Agent : "+userAgent + "; IP :" + ip);
/**
* 打印url 和方法名
*/
logger.info("URL : " + request.getRequestURL().toString()+" Http_Method : "+request.getMethod());
/**
* 获取所有参数方法:
*/
Enumeration<String> enu=request.getParameterNames();
if(enu.hasMoreElements()) {
StringBuffer params = new StringBuffer();
while (enu.hasMoreElements()) {
String paraName = enu.nextElement();
params.append(paraName + ": " + request.getParameter(paraName) + " ");
}
logger.info("Params : " + params.toString());
}
}
@AfterReturning("webLog()")
public void doAfterReturning(JoinPoint joinPoint){
/**
* 处理完请求,返回内容
*/
logger.info("耗时(毫秒) : " + (System.currentTimeMillis()- startTime.get()));
logger.info("\r\n----------方法结束----------\n\n\n");
}
/**
* 打印cookie信息
* @param cookies
* @return
*/
private String getCookieInfo(Cookie[] cookies){
if(cookies!=null){
StringBuffer sbCookie = new StringBuffer();
for(Cookie cookie:cookies){
sbCookie.append(cookie.getName()+":"+cookie.getValue());
}
return sbCookie.toString();
}
return "";
}
private static final String[] HEADERS_TO_TRY = { "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR", "X-Real-IP" };
/**
*
* getClientIpAddress:(获取用户ip,可穿透代理). <br/>
*
* @author Songsir
* @Date 2018年3月2日下午4:41:47
* @param request
* @return
* @since JDK 1.8
*/
public static String getClientIpAddress(HttpServletRequest request) {
for (String header : HEADERS_TO_TRY) {
String ip = request.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr();
}
}