AOP在專案方法日誌列印方面的應用
阿新 • • 發佈:2018-11-10
@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(); } }