• srpingboot 对每个请求 参数 和 响应结果 进行日志打印


    HttpAspect.java

    注意这里需要改成拦截对包:
    @Pointcut("execution(* cn.rc.api..*.*(..))") public void log() {}
    package cn.rc.common.filter;
    
    import com.alibaba.fastjson.JSONObject;
    import org.apache.commons.lang.ArrayUtils;
    import org.apache.commons.lang.RandomStringUtils;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.*;
    import org.aspectj.lang.reflect.MethodSignature;
    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.text.SimpleDateFormat;
    import java.util.*;
    
    @Aspect
    @Component
    public class HttpAspect {
    
        public static ThreadLocal<Map<String,Object>> requsetLogKey = new ThreadLocal();
    
        /**
         * 这样写是将重复的代码提取出来方便处理
         */
        @Pointcut("execution(* cn.rc.api..*.*(..))")
        public void log() {}
    
    
        @Before("log()")
        public void doBefore(JoinPoint joinPoint) {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
    
            Date d=new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date=simpleDateFormat.format(d);
    
            StringBuffer url=request.getRequestURL();
            String method=request.getMethod();
            String ip=request.getRemoteAddr();
            String class_method=joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
            Object[] args=joinPoint.getArgs();
            String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();//参数名
    
    
            //记录请求耗时
            //生成一个随机字符串
            String key= RandomStringUtils.randomAlphanumeric(10);
            //存入ThreadLocal,当controller方法执行完,或者报错的时候,可以查看到是哪个请求
            long start = System.currentTimeMillis();
            Map map=new HashMap();
            map.put("requestKey",key);
            map.put("currentTime",start);
            map.put("class_method",class_method);
    
            requsetLogKey.set(map);
    
            StringBuffer s=new StringBuffer();
            s.append(date+":   ");
            s.append("url="+url+"    ");
            s.append("method="+method+"    ");
            s.append("ip="+ip+"    ");
            s.append("class_method="+class_method+"    ");
            List a=new ArrayList<>();
            for (int i =0;i<argNames.length;i++){
                String n= argNames[i];
                String v="";
                if(args[i]!=null){
                    v=(args[i]).toString();
                }else{
                    v="null";
                }
                a.add(n+"="+v);
            }
            s.append("args="+ ArrayUtils.toString(a)+"    ");
    
            System.out.println("[requestKey::"+key+"]--"+s.toString() );
        }
    
    
        /*@After("log()")
        public void doAfter() {
            System.out.println("方法正常完成!");
        }*/
    
        @AfterReturning(returning = "obj",pointcut = "log()")
        public void doAfterReturning(Object obj) {
            String resultJson = JSONObject.toJSONString(obj);
    
            //计算方法请求耗时
            Map map=requsetLogKey.get();
            requsetLogKey.remove();
            String key=(String)map.get("requestKey");
            Long startTime=(Long)map.get("currentTime");
            long elapseTime = System.currentTimeMillis() - startTime;
            String class_method=(String)map.get("class_method");//执行的方法路径
    
            System.out.println("[requestKey::"+key+"]--responseSucceeded:"+resultJson );
            System.out.println("[requestKey::"+key+"]--method"+class_method+"--耗时:"+elapseTime);
        }
    
        @AfterThrowing(throwing="ex",pointcut="log()")
        public void doRecoveryActions(Throwable ex) {
    
            //计算方法请求耗时
            Map map=requsetLogKey.get();
            requsetLogKey.remove();
            String key=(String)map.get("requestKey");
            Long startTime=(Long)map.get("currentTime");
            long elapseTime = System.currentTimeMillis() - startTime;
            String class_method=(String)map.get("class_method");//执行的方法路径
            System.out.println("[requestKey::"+key+"]--error"+ex );
            System.out.println("[requestKey::"+key+"]--requestErrorMethod"+class_method+"--耗时:"+elapseTime );
        }
    }
     

    调用接口:

  • 相关阅读:
    struts1——静态ActionForm与动态ActionForm
    【入门篇】ANDROID开发之BUG专讲
    oracle undo 复杂度--oracle核心技术读书笔记四
    linux高级技巧:rsync同步(二)
    【c语言】数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字
    一维动态数组和二维动态数组的创建和使用
    HDU 1788 Chinese remainder theorem again 中国剩余定理
    直接选择排序
    使用enca进行字符集转码
    拒绝switch,程序加速之函数指针数组
  • 原文地址:https://www.cnblogs.com/wanjun-top/p/12912155.html
Copyright © 2020-2023  润新知