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();
}
网友评论