1. 程式人生 > 實用技巧 >Spring AOP攔截並列印controller層請求日誌

Spring AOP攔截並列印controller層請求日誌

/**
 * Aop implementation of request log printing
 *
 * Created b on 9:07 2017/10/27
 */
@Component
@Aspect
public class RequestLog {

    public static final Logger LOG = LoggerFactory.getLogger(RequestLog.class);

    /**
     * Define a pointcut
     */
//    @Pointcut("execution(* com.wqxia.*.*(..))")
    @Pointcut("@annotation(com.wqxia.common.log.annotation.SystemLog)")
    
public void controllerLog() {} /** * Print Log before controller * @param joinPoint */ @Before("controllerLog()") public void before(JoinPoint joinPoint) throws Exception { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); LOG.info(
"請求IP:{}", request.getRemoteAddr()); LOG.info("請求路徑:{}", request.getRequestURL()); LOG.info("請求方式:{}", request.getMethod()); LOG.info("方法描述:{}", getMethodDescription(joinPoint)); LOG.info("請求引數:{}", JSONObject.toJSONString(request.getParameterMap())); } /** * Print the time that request method execution spend *
@param joinPoint * @throws Throwable */ @Around("controllerLog()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); Object[] args = joinPoint.getArgs(); Object retVal = joinPoint.proceed(args); long endTime = System.currentTimeMillis(); LOG.info("執行時間:{} ms", endTime - startTime); LOG.info("返回值:{}\n\t", JsonUtils.obj2Json(retVal)); return retVal; } /** * Print exception * @param ex */ @AfterThrowing(throwing = "ex", pointcut = "controllerLog()") public void afterThrowing(Throwable ex) { LOG.error("發生異常:{}", ex.toString()); } /** * Acquire the description for annotation target method * @param joinPoint * @return * @throws Exception */ protected String getMethodDescription(JoinPoint joinPoint) throws Exception { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class<?> targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); String description = ""; for (Method method : methods) { if(method.getName().equals(methodName)) { Class<?>[] clazzs = method.getParameterTypes(); if(clazzs.length == arguments.length) { description = method.getAnnotation(SystemLog.class).description(); break; } } } return description; } }
註解:
/**
 * System log annotation for controller or service
 * Created on 9:10 2017/11/2
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemLog {

    String description() default "";
}
註解加在controller層方法上即可