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


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;

/**
 * 

改变Bean的日志级别,可以让它不打印日志 * 具体使用是在日之类上加上@NoLogBeanPostProcessor.NoLog即可。 *

* * * @RestController * @NoLogBeanPostProcessor.NoLog * public logController { * * } * * @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 noLogClasses= Collections.synchronizedList(new ArrayList<>()); final ch.qos.logback.classic.LoggerContext loggerContext = (ch.qos.logback.classic.LoggerContext) LoggerFactory.getILoggerFactory(); }

你可能感兴趣的:(使用注解让SL4j打不出日志出来)