使用AOP编程思想,打印日志,输出请求信息,便于查找错误。


/**
 * 切面 日志
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    //Logger logger= Logger.getLogger(LogAspect.class);
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
    long startTime ;
    long endTime;

    /**
     * 切点
     */
    @Pointcut(value = "(execution(* com.how2java..web.*.*(..)))")
    public void log(){

    }

    /**
     * 前置通知
     * @param joinpoint
     */
    @Before(value = "log()")
    public void doBefore(JoinPoint joinpoint){
        log.info("前置通知");
        startTime = System.currentTimeMillis();
        //请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        StringBuffer sb = new StringBuffer();
        //请求url
        String reqUrl = request.getRequestURL().toString();
        String method = request.getMethod();
        sb.append("请求url:" + reqUrl + "  " + method + "\n");

//        if(request.getMethod().equalsIgnoreCase(RequestMethod.GET.name())){
//            Map parameterMap = request.getParameterMap();
//            Map paramMap = new HashMap<>();
//            parameterMap.forEach((key, value) -> paramMap.put(key, Arrays.stream(value)
//                    .collect(Collectors.joining(","))));
//            sb.append("请求内容:"+JSON.toJSONString(paramMap));
            Object[] args = joinpoint.getArgs();
            String[] params = ((CodeSignature)joinpoint.getSignature()).getParameterNames();
            for(int i=0;i sb1.append(object.toString().replace("=",":")));
//            if(sb1.length() == 0){
//                sb1.append("{}");
//            }
//            sb1.append("请求参数:"+sb1.toString());
//        }
        log.info("请求:{}",sb.toString());


    }

    /**
     * 后置通知
     */
    @After(value = "log()")
    public void doAfter(){
        endTime = System.currentTimeMillis();

        log.info("后置通知:间隔时间:{}",String.valueOf(endTime-startTime));
    }
    @AfterThrowing(pointcut = "log()",throwing = "e")
    public void handleThrowing(JoinPoint joinPoint, Exception e){
       log.info("出现了异常{}",e.getMessage());
    }
}

 

你可能感兴趣的:(springboot)