SpringAOP 实现日志打印

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));
        }

    }

}

猜你喜欢

转载自blog.csdn.net/luoyeyeyu/article/details/83512752