将spring bean注入自定义的logback过滤器 [英] Inject spring bean into custom logback filter
问题描述
为了减少应用程序中存在的日志记录数量,我们决定 启用/禁用基于每个客户端的某些方法的日志记录.
in order to reduce the amount of logging present in our application, we decided to enable/disable logging of certain methods on a per-client basis.
public class LoggingFilter extends Filter<ILoggingEvent> {
@Autowired
private MethodNameValidator validator;
@Override
public FilterReply decide(ILoggingEvent event) {
Map<String, String> mdcProperties = event.getMDCPropertyMap();
if (mdcProperties.isEmpty()) {
return FilterReply.ACCEPT;
}
String accountId = mdcProperties.get(MDCUtil.ACCOUNT_ID);
String methodName = mdcProperties.get(MDCUtil.METHOD_NAME);
if (validator.isValidMethodName(accountId, methodName)) {
return FilterReply.ACCEPT;
}
return FilterReply.DENY;
}
}
上面定义的自定义过滤器具有一个验证组件,在其中实现了方法验证逻辑.
The custom filter defined above has a validation component in which the method validation logic is implemented.
验证器是Spring Bean(也通过JMX公开用于外部配置).
The validator is a Spring Bean (which is also exposed via JMX for external configuration).
我无法将MethodNameValidator bean注入到过滤器中.
I fail to inject the MethodNameValidator bean into the filter.
过滤器也是bean.
有没有办法做到这一点?
Is there a way to achieve this?
如果我可以动态设置回退过滤器 然后我可以将过滤器初始化为bean,获取所需的记录器 按名称并应用过滤器.
If I could set a logback filter dynamically then I could initialize my filter as a bean, get the desired logger by name and apply the filter.
无法弄清楚如何通过提供的Logback api进行操作.
Can't figure out how to do it via the provided Logback api.
推荐答案
这对我有用.
@Component
public class DiscoveringPostProcessor implements BeanPostProcessor, ApplicationContextAware {
ApplicationContext applicationContext;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof CustomLoggingFilter){
Map<String, TurboFilter> filterBeans = applicationContext.getBeansOfType(TurboFilter.class);
for (TurboFilter filter : filterBeans.values()) {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.addTurboFilter(filter);
}
}
return bean;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
2.
@Named("customLoggingFilter")
public class CustomLoggingFilter extends TurboFilter {
@Autowired
private TestService ts;
@Override
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
System.out.println(ts.doTest());
return FilterReply.ACCEPT;
}
}
这篇关于将spring bean注入自定义的logback过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!