1. 程式人生 > >spring/spring boot 自定義日誌註解輸出請求引數和結果

spring/spring boot 自定義日誌註解輸出請求引數和結果

@Aspect
@Component
public class LoggerAdvice {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 在這裡定義切面的點,Pointcut的表示式語法需要匹配到你呼叫的方法中
     */
    @Pointcut("within(cn.hlvan.citywide.controller..*)")
    public void declareJoinPointExpression() {
    }

    @Before("declareJoinPointExpression()")
    public void addBeforeLogger(JoinPoint joinPoint) {
        try {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();

            String url = request.getRequestURL().toString();
            String method = request.getMethod();
            String uri = request.getRequestURI();
            String userAgent = request.getHeader("User-Agent");
            Cookie cookie = null;
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if (c.getName().endsWith("Token")) {
                        cookie = c;
                        break;
                    }
                }
            }
            String CookieString=cookie==null?"":GsonUtils.getInstance().toJson(cookie);
            String params = GsonUtils.toJson(request.getParameterMap());

            String apiName = "";
            String targetName = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            Object[] arguments = joinPoint.getArgs();
            Class targetClass = Class.forName(targetName);
            Method[] methods = targetClass.getMethods();

            for (Method m : methods) {
                if (m.getName().equals(methodName)) {
                    Class[] clazzs = m.getParameterTypes();
                    if (clazzs.length == arguments.length) {
                        if (m.getDeclaredAnnotation(LoggerManage.class) != null) {
                            apiName = m.getDeclaredAnnotation(LoggerManage.class).description();
                            break;
                        }
                    }
                }
            }
            logger.info("apiName:{}, url: {},uri: {}, method: {}, params: {},Cookie:{},UserAgent:{}",
                apiName,url,uri, method, params, CookieString,userAgent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

//    @AfterReturning(value = "declareJoinPointExpression()", returning = "returnObj")
//    public void addAfterReturningLogger(JoinPoint joinPoint, Object returnObj) {
//        System.out.println("結束");
//    }

//    @AfterThrowing(pointcut = "declareJoinPointExpression()", throwing = "ex")
//    public void addAfterThrowingLogger(JoinPoint joinPoint, Exception ex) {
//        System.out.println("異常");
//    }
    @Around(value = "declareJoinPointExpression()")
    public Object doAround(ProceedingJoinPoint proceeding) throws Throwable {
        long beforeTime=System.currentTimeMillis();
        //執行被攔截的方法 result是返回結果
        Object result = proceeding.proceed();
        //debug模式下才計算方法耗時
        if (logger.isDebugEnabled()) {
            long afterTime=System.currentTimeMillis();
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();
            logger.info("請求:{} , 耗時:{}ms",request.getRequestURI(),afterTime-beforeTime);
        }
        //此處可以在log輸出result,依據業務要求處理
        return result;
    }
}