美文网首页
使用注解让SL4j打不出日志出来

使用注解让SL4j打不出日志出来

作者: 艺术类架构师 | 来源:发表于2019-06-21 14:35 被阅读0次
    
    import ch.qos.logback.classic.Level;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanPostProcessor;
    import org.springframework.stereotype.Component;
    
    import java.lang.annotation.*;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    /**
     * <p>改变Bean的日志级别,可以让它不打印日志
     * 具体使用是在日之类上加上@NoLogBeanPostProcessor.NoLog即可。
     * </p>
     *
     * <code>
     *      @RestController
     *      @NoLogBeanPostProcessor.NoLog
     *     public logController {
     *
     *     }
     * </code>
     * @Author Lycol
     */
    @Component
    public class NoLogBeanPostProcessor implements BeanPostProcessor{
    
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            if(bean.getClass().isAnnotationPresent(NoLog.class)){
                noLogClasses.add(bean.getClass());
    
            }
            return bean;
        }
    
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    
            for(Class clazz: noLogClasses){
                ch.qos.logback.classic.Logger target = loggerContext.getLogger(clazz);
                target.setLevel(Level.OFF);
            }
            return bean;
        }
        @Target(ElementType.TYPE)
        @Retention(RetentionPolicy.RUNTIME)
        @Documented
        public   @interface  NoLog{
    
    
        }
    
        private List<Class> noLogClasses= Collections.synchronizedList(new ArrayList<>());
    
        final   ch.qos.logback.classic.LoggerContext loggerContext = (ch.qos.logback.classic.LoggerContext) LoggerFactory.getILoggerFactory();
    }
    
    

    相关文章

      网友评论

          本文标题:使用注解让SL4j打不出日志出来

          本文链接:https://www.haomeiwen.com/subject/ltvyqctx.html