SpringAOP 實現日誌列印
阿新 • • 發佈:2018-12-18
1、添加註解掃描和支援AOP的牌子
<context:component-scan base-package="com.sp8.web.aop"/>
<aop:aspectj-autoproxy proxy-target-class="true" />
2、不囉嗦,程式碼示例:
package com.sp8.web.aop; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; 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.springframework.beans.factory.annotation.Autowired; 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; import java.util.HashMap; import java.util.Map; /** * 列印請求的入參和出參以及用時,幫助更好的分析程式 * <p> */ @Slf4j @Aspect @Component public class RequestLogAdvice { @Autowired private UccClient uccClient; @Pointcut(value = "execution(* com.sp8.web.controller.*.*.*(..)) || execution(* com.sp8.web.controller.*.*(..))") public void pointcut() { } @Around("pointcut()") public Object handle(ProceedingJoinPoint joinPoint) throws Throwable { Long startTime = System.currentTimeMillis(); preHandle(); Object retVal = joinPoint.proceed(); postHandle(retVal, startTime); return retVal; } private void preHandle() { if (uccClient.on("Sp8_requestLogOpen")) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String requestPath = request.getRequestURI(); //查詢全部入參 Enumeration<String> paramNames = request.getParameterNames(); Map<String, Object> paramsMap = new HashMap<>(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); paramsMap.put(paramName, request.getParameter(paramName)); } log.info("\n ----------------------------request[{}]--start--[userPin:{}, reqest params:{}]----------", requestPath, Sp8Context.getSp8Context().getPin(), paramsMap); } } private void postHandle(Object retVal, Long startTime) { if (uccClient.on("Sp8_requestLogOpen")) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); Long useTime = System.currentTimeMillis() - startTime; String requestPath = request.getRequestURI(); log.info("\n ----------------------------response[{}]--end--[userPin:{}, 耗時:{},response result:{}]----------\n", requestPath, Sp8Context.getSp8Context().getPin(), useTime, JSONObject.toJSONString(retVal)); } } }