Table des matières
1.背景   
2.设计思路
3.核心代码
3.1 自定义注解
3.2 实现BeanFactoryPostProcessor接口
3.3 实现MethodInterceptor编写打印日志逻辑
3.4 实现BeanPostProcessor接口
3.5 启动类配置注解
4.出现的问题(及其解决办法)
Maison Java javaDidacticiel Comment réaliser une impression unifiée des journaux des paramètres d'entrée et des paramètres de sortie en Java

Comment réaliser une impression unifiée des journaux des paramètres d'entrée et des paramètres de sortie en Java

May 10, 2023 pm 03:37 PM
java

    1.背景   

    SpringBoot项目中,之前都是在controller方法的第一行手动打印 log,return之前再打印返回值。有多个返回点时,就需要出现多少重复代码,过多的非业务代码显得十分凌乱。

    本文将采用AOP 配置自定义注解实现 入参、出参的日志打印(方法的入参和返回值都采用 fastjson 序列化)。

    2.设计思路

    将特定包下所有的controller生成代理类对象,并交由Spring容器管理,并重写invoke方法进行增强(入参、出参的打印).

    3.核心代码

    3.1 自定义注解

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Import({InteractRecordBeanPostProcessor.class})
    public @interface EnableInteractRecord {
    
        /**
         * app对应controller包名
         */
        String[] basePackages() default {};
    
        /**
         * 排除某些包
         */
        String[] exclusions() default {};
    
    }
    Copier après la connexion

    3.2 实现BeanFactoryPostProcessor接口

    作用:获取EnableInteractRecord注解对象,用于获取需要创建代理对象的包名,以及需要排除的包名

    @Component
    public class InteractRecordFactoryPostProcessor implements BeanFactoryPostProcessor {
    
        private static Logger logger = LoggerFactory.getLogger(InteractRecordFactoryPostProcessor.class);
    
        private EnableInteractRecord enableInteractRecord;
    
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            try {
                String[] names = beanFactory.getBeanNamesForAnnotation(EnableInteractRecord.class);
                for (String name : names) {
                    enableInteractRecord = beanFactory.findAnnotationOnBean(name, EnableInteractRecord.class);
                    logger.info("开启交互记录 ", enableInteractRecord);
                }
            } catch (Exception e) {
                logger.error("postProcessBeanFactory() Exception ", e);
            }
        }
    
        public EnableInteractRecord getEnableInteractRecord() {
            return enableInteractRecord;
        }
    
    }
    Copier après la connexion

    3.3 实现MethodInterceptor编写打印日志逻辑

    作用:进行入参、出参打印,包含是否打印逻辑

    @Component
    public class ControllerMethodInterceptor implements MethodInterceptor {
        private static Logger logger = LoggerFactory.getLogger(ControllerMethodInterceptor.class);
        // 请求开始时间
        ThreadLocal<Long> startTime = new ThreadLocal<>();
        private String localIp = "";
    
        @PostConstruct
        public void init() {
            try {
                localIp = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                logger.error("本地IP初始化失败 : ", e);
            }
        }
    
        @Override
        public Object invoke(MethodInvocation invocation) {
            pre(invocation);
            Object result;
            try {
                result = invocation.proceed();
                post(invocation, result);
                return result;
            } catch (Throwable ex) {
                logger.error("controller 执行异常: ", ex);
                error(invocation, ex);
            }
    
            return null;
    
        }
    
        public void error(MethodInvocation invocation, Throwable ex) {
            String msgText = ex.getMessage();
            logger.info(startTime.get() + " 异常,请求结束");
            logger.info("RESPONSE : " + msgText);
            logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
        }
    
        private void pre(MethodInvocation invocation) {
            long now = System.currentTimeMillis();
            startTime.set(now);
            logger.info(now + " 请求开始");
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
    
            logger.info("URL : " + request.getRequestURL().toString());
            logger.info("HTTP_METHOD : " + request.getMethod());
            logger.info("REMOTE_IP : " + getRemoteIp(request));
            logger.info("LOCAL_IP : " + localIp);
            logger.info("METHOD : " + request.getMethod());
            logger.info("CLASS_METHOD : " + getTargetClassName(invocation) + "." + invocation.getMethod().getName());
    
            // 获取请求头header参数
            Map<String, String> map = new HashMap<String, String>();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String key = (String) headerNames.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
            logger.info("HEADERS : " + JSONObject.toJSONString(map));
            Date createTime = new Date(now);
            // 请求报文
            Object[] args = invocation.getArguments();// 参数
            String msgText = "";
            Annotation[][] annotationss = invocation.getMethod().getParameterAnnotations();
    
            for (int i = 0; i < args.length; i++) {
                Object arg = args[i];
                if (!(arg instanceof ServletRequest)
                        && !(arg instanceof ServletResponse)
                        && !(arg instanceof Model)) {
                    RequestParam rp = null;
                    Annotation[] annotations = annotationss[i];
                    for (Annotation annotation : annotations) {
                        if (annotation instanceof RequestParam) {
                            rp = (RequestParam) annotation;
                        }
                    }
                    if (msgText.equals("")) {
                        msgText += (rp != null ? rp.value() + " = " : " ") + JSONObject.toJSONString(arg);
                    } else {
                        msgText += "," + (rp != null ? rp.value() + " = " : " ") + JSONObject.toJSONString(arg);
                    }
                }
            }
            logger.info("PARAMS : " + msgText);
        }
    
        private void post(MethodInvocation invocation, Object result) {
            logger.info(startTime.get() + " 请求结束");
            if (!(result instanceof ModelAndView)) {
                String msgText = JSONObject.toJSONString(result);
                logger.info("RESPONSE : " + msgText);
            }
            logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
    
        }
    
    
        private String getRemoteIp(HttpServletRequest request) {
            String remoteIp = null;
            String remoteAddr = request.getRemoteAddr();
            String forwarded = request.getHeader("X-Forwarded-For");
            String realIp = request.getHeader("X-Real-IP");
            if (realIp == null) {
                if (forwarded == null) {
                    remoteIp = remoteAddr;
                } else {
                    remoteIp = remoteAddr + "/" + forwarded.split(",")[0];
                }
            } else {
                if (realIp.equals(forwarded)) {
                    remoteIp = realIp;
                } else {
                    if (forwarded != null) {
                        forwarded = forwarded.split(",")[0];
                    }
                    remoteIp = realIp + "/" + forwarded;
                }
            }
            return remoteIp;
        }
    
        private String getTargetClassName(MethodInvocation invocation) {
            String targetClassName = "";
            try {
                targetClassName = AopTargetUtils.getTarget(invocation.getThis()).getClass().getName();
            } catch (Exception e) {
                targetClassName = invocation.getThis().getClass().getName();
            }
            return targetClassName;
        }
    
    }
    Copier après la connexion

    AopTargetUtils:

    public class AopTargetUtils {  
      
          
        /** 
         * 获取 目标对象 
         * @param proxy 代理对象 
         * @return  
         * @throws Exception 
         */  
        public static Object getTarget(Object proxy) throws Exception {  
              
            if(!AopUtils.isAopProxy(proxy)) {
                return proxy;//不是代理对象  
            }  
              
            if(AopUtils.isJdkDynamicProxy(proxy)) {
                return getJdkDynamicProxyTargetObject(proxy);  
            } else { //cglib  
                return getCglibProxyTargetObject(proxy);  
            }  
              
              
              
        }  
      
      
        private static Object getCglibProxyTargetObject(Object proxy) throws Exception {  
            Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");  
            h.setAccessible(true);
            Object dynamicAdvisedInterceptor = h.get(proxy);  
              
            Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");  
            advised.setAccessible(true);  
              
            Object target = ((AdvisedSupport)advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
              
            return getTarget(target);
        }  
      
      
        private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {  
            Field h = proxy.getClass().getSuperclass().getDeclaredField("h");  
            h.setAccessible(true);  
            AopProxy aopProxy = (AopProxy) h.get(proxy);
              
            Field advised = aopProxy.getClass().getDeclaredField("advised");  
            advised.setAccessible(true);  
              
            Object target = ((AdvisedSupport)advised.get(aopProxy)).getTargetSource().getTarget();
              
            return getTarget(target); 
        }  
          
    }
    Copier après la connexion

    3.4 实现BeanPostProcessor接口

    作用:筛选出需要生成代理的类,并生成代理类,返回给Spring容器管理。

    public class InteractRecordBeanPostProcessor implements BeanPostProcessor {
    
        private static Logger logger = LoggerFactory.getLogger(InteractRecordBeanPostProcessor.class);
    
        @Autowired
        private InteractRecordFactoryPostProcessor interactRecordFactoryPostProcessor;
    
        @Autowired
        private ControllerMethodInterceptor controllerMethodInterceptor;
    
        private String BASE_PACKAGES[];//需要拦截的包
    
        private String EXCLUDING[];// 过滤的包
    
        //一层目录匹配
        private static final String ONE_REGEX = "[a-zA-Z0-9_]+";
    
        //多层目录匹配
        private static final String ALL_REGEX = ".*";
    
        private static final String END_ALL_REGEX = "*";
    
        @PostConstruct
        public void init() {
            EnableInteractRecord ir = interactRecordFactoryPostProcessor.getEnableInteractRecord();
            BASE_PACKAGES = ir.basePackages();
            EXCLUDING = ir.exclusions();
        }
    
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            try {
                if (interactRecordFactoryPostProcessor.getEnableInteractRecord() != null) {
                    // 根据注解配置的包名记录对应的controller层
                    if (BASE_PACKAGES != null && BASE_PACKAGES.length > 0) {
                        Object proxyObj = doEnhanceForController(bean);
                        if (proxyObj != null) {
                            return proxyObj;
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("postProcessAfterInitialization() Exception ", e);
            }
            return bean;
        }
    
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }
    
        private Object doEnhanceForController(Object bean) {
            String beanPackageName = getBeanPackageName(bean);
            if (StringUtils.isNotBlank(beanPackageName)) {
                for (String basePackage : BASE_PACKAGES) {
                    if (matchingPackage(basePackage, beanPackageName)) {
                        if (EXCLUDING != null && EXCLUDING.length > 0) {
                            for (String excluding : EXCLUDING) {
                                if (matchingPackage(excluding, beanPackageName)) {
                                    return bean;
                                }
                            }
                        }
                        Object target = null;
                        try {
                            target = AopTargetUtils.getTarget(bean);
                        } catch (Exception e) {
                            logger.error("AopTargetUtils.getTarget() exception", e);
                        }
                        if (target != null) {
                            boolean isController = target.getClass().isAnnotationPresent(Controller.class);
                            boolean isRestController = target.getClass().isAnnotationPresent(RestController.class);
                            if (isController || isRestController) {
                                ProxyFactory proxy = new ProxyFactory();
                                proxy.setTarget(bean);
                                proxy.addAdvice(controllerMethodInterceptor);
                                return proxy.getProxy();
                            }
                        }
                    }
                }
    
            }
            return null;
        }
    
        private static boolean matchingPackage(String basePackage, String currentPackage) {
            if (StringUtils.isEmpty(basePackage) || StringUtils.isEmpty(currentPackage)) {
                return false;
            }
            if (basePackage.indexOf("*") != -1) {
                String patterns[] = StringUtils.split(basePackage, ".");
                for (int i = 0; i < patterns.length; i++) {
                    String patternNode = patterns[i];
                    if (patternNode.equals("*")) {
                        patterns[i] = ONE_REGEX;
                    }
                    if (patternNode.equals("**")) {
                        if (i == patterns.length - 1) {
                            patterns[i] = END_ALL_REGEX;
                        } else {
                            patterns[i] = ALL_REGEX;
                        }
                    }
                }
                String basePackageRegex = StringUtils.join(patterns, "\\.");
                Pattern r = Pattern.compile(basePackageRegex);
                Matcher m = r.matcher(currentPackage);
                return m.find();
            } else {
                return basePackage.equals(currentPackage);
            }
        }
    
        private String getBeanPackageName(Object bean) {
            String beanPackageName = "";
            if (bean != null) {
                Class<?> beanClass = bean.getClass();
                if (beanClass != null) {
                    Package beanPackage = beanClass.getPackage();
                    if (beanPackage != null) {
                        beanPackageName = beanPackage.getName();
                    }
                }
            }
            return beanPackageName;
        }
    
    }
    Copier après la connexion

    3.5 启动类配置注解

    @EnableInteractRecord(basePackages = “com.test.test.controller”,exclusions = “com.test.demo.controller”)
    Copier après la connexion

    以上即可实现入参、出参日志统一打印,并且可以将特定的controller集中管理,并不进行日志的打印(及不进生成代理类)。

    4.出现的问题(及其解决办法)

    实际开发中,特定不需要打印日志的接口,无法统一到一个包下。大部分需要打印的接口,和不需要打印的接口,大概率会参杂在同一个controller中,根据以上设计思路,无法进行区分。

    解决办法:

    自定义排除入参打印注解

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface ExcludeReqLog {
    }
    Copier après la connexion

    自定义排除出参打印注解

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface ExcludeRespLog {
    }
    Copier après la connexion

    增加逻辑

    // 1.在解析requestParam之前进行判断
            Method method = invocation.getMethod();
            Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
            boolean flag = true;
            for (Annotation annotation : declaredAnnotations) {
                if (annotation instanceof ExcludeReqLog) {
                    flag = false;
                }
            }
            if (!flag) {
                logger.info("该方法已排除,不打印入参");
                return;
            }
    // 2.在解析requestResp之前进行判断
            Method method = invocation.getMethod();
            Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
            boolean flag = true;
            for (Annotation annotation : declaredAnnotations) {
                if (annotation instanceof ExcludeRespLog) {
                    flag = false;
                }
            }
            if (!flag) {
                logger.info("该方法已排除,不打印出参");
                return;
            }
    Copier après la connexion

    使用方法

    // 1.不打印入参
        @PostMapping("/uploadImg")
        @ExcludeReqLog
        public Result<List<Demo>> uploadIdeaImg(@RequestParam(value = "imgFile", required = false) MultipartFile[] imgFile) {
            return demoService.uploadIdeaImg(imgFile);
        }
    //2.不打印出参
        @PostMapping("/uploadImg")
        @ExcludeRespLog 
        public Result<List<Demo>> uploadIdeaImg(@RequestParam(value = "imgFile", required = false) MultipartFile[] imgFile) {
            return demoService.uploadIdeaImg(imgFile);
        }
    Copier après la connexion

    Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

    Déclaration de ce site Web
    Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

    Outils d'IA chauds

    Undresser.AI Undress

    Undresser.AI Undress

    Application basée sur l'IA pour créer des photos de nu réalistes

    AI Clothes Remover

    AI Clothes Remover

    Outil d'IA en ligne pour supprimer les vêtements des photos.

    Undress AI Tool

    Undress AI Tool

    Images de déshabillage gratuites

    Clothoff.io

    Clothoff.io

    Dissolvant de vêtements AI

    AI Hentai Generator

    AI Hentai Generator

    Générez AI Hentai gratuitement.

    Article chaud

    R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
    3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Meilleurs paramètres graphiques
    3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Comment réparer l'audio si vous n'entendez personne
    3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: Comment déverrouiller tout dans Myrise
    4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

    Outils chauds

    Bloc-notes++7.3.1

    Bloc-notes++7.3.1

    Éditeur de code facile à utiliser et gratuit

    SublimeText3 version chinoise

    SublimeText3 version chinoise

    Version chinoise, très simple à utiliser

    Envoyer Studio 13.0.1

    Envoyer Studio 13.0.1

    Puissant environnement de développement intégré PHP

    Dreamweaver CS6

    Dreamweaver CS6

    Outils de développement Web visuel

    SublimeText3 version Mac

    SublimeText3 version Mac

    Logiciel d'édition de code au niveau de Dieu (SublimeText3)

    Nombre parfait en Java Nombre parfait en Java Aug 30, 2024 pm 04:28 PM

    Guide du nombre parfait en Java. Nous discutons ici de la définition, comment vérifier le nombre parfait en Java ?, des exemples d'implémentation de code.

    Générateur de nombres aléatoires en Java Générateur de nombres aléatoires en Java Aug 30, 2024 pm 04:27 PM

    Guide du générateur de nombres aléatoires en Java. Nous discutons ici des fonctions en Java avec des exemples et de deux générateurs différents avec d'autres exemples.

    Weka en Java Weka en Java Aug 30, 2024 pm 04:28 PM

    Guide de Weka en Java. Nous discutons ici de l'introduction, de la façon d'utiliser Weka Java, du type de plate-forme et des avantages avec des exemples.

    Numéro de Smith en Java Numéro de Smith en Java Aug 30, 2024 pm 04:28 PM

    Guide du nombre de Smith en Java. Nous discutons ici de la définition, comment vérifier le numéro Smith en Java ? exemple avec implémentation de code.

    Questions d'entretien chez Java Spring Questions d'entretien chez Java Spring Aug 30, 2024 pm 04:29 PM

    Dans cet article, nous avons conservé les questions d'entretien Java Spring les plus posées avec leurs réponses détaillées. Pour que vous puissiez réussir l'interview.

    Break or Return of Java 8 Stream Forach? Break or Return of Java 8 Stream Forach? Feb 07, 2025 pm 12:09 PM

    Java 8 présente l'API Stream, fournissant un moyen puissant et expressif de traiter les collections de données. Cependant, une question courante lors de l'utilisation du flux est: comment se casser ou revenir d'une opération FOREAK? Les boucles traditionnelles permettent une interruption ou un retour précoce, mais la méthode Foreach de Stream ne prend pas directement en charge cette méthode. Cet article expliquera les raisons et explorera des méthodes alternatives pour la mise en œuvre de terminaison prématurée dans les systèmes de traitement de flux. Lire plus approfondie: Améliorations de l'API Java Stream Comprendre le flux Forach La méthode foreach est une opération terminale qui effectue une opération sur chaque élément du flux. Son intention de conception est

    Horodatage à ce jour en Java Horodatage à ce jour en Java Aug 30, 2024 pm 04:28 PM

    Guide de TimeStamp to Date en Java. Ici, nous discutons également de l'introduction et de la façon de convertir l'horodatage en date en Java avec des exemples.

    Créer l'avenir : programmation Java pour les débutants absolus Créer l'avenir : programmation Java pour les débutants absolus Oct 13, 2024 pm 01:32 PM

    Java est un langage de programmation populaire qui peut être appris aussi bien par les développeurs débutants que par les développeurs expérimentés. Ce didacticiel commence par les concepts de base et progresse vers des sujets avancés. Après avoir installé le kit de développement Java, vous pouvez vous entraîner à la programmation en créant un simple programme « Hello, World ! ». Une fois que vous avez compris le code, utilisez l'invite de commande pour compiler et exécuter le programme, et « Hello, World ! » s'affichera sur la console. L'apprentissage de Java commence votre parcours de programmation et, à mesure que votre maîtrise s'approfondit, vous pouvez créer des applications plus complexes.

    See all articles