因为logback日志是在ServletContext中加载的,这时候是使用不了spring加载的zk对象来获取配置的,我的想法是等spring容器加载完成后,再通过spring 上下文获取ServletContext,设置logback里面配置,最后通过ch.qos.logback.ext.spring.web.WebLogbackConfigurer将zk配置读取到logback的上下文,操作步骤如下
1.定义AddLogbackSettingListener ,该包必须被注解扫描到
package com.tzg.app.listener;
import ch.qos.logback.ext.spring.web.WebLogbackConfigurer;
import com.dangdang.config.service.zookeeper.ZookeeperConfigGroup;
import javax.servlet.ServletContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
@Component
public class AddLogbackSettingListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event)
{
if(event.getApplicationContext() instanceof XmlWebApplicationContext){
try {
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ZookeeperConfigGroup esConfig = (ZookeeperConfigGroup) webApplicationContext.getBean("esConfig");
String kafkaUrl = esConfig.get("kafka.url");
ServletContext sc = webApplicationContext.getServletContext();
System.setProperty("KAFKA.SERVER", kafkaUrl);
WebLogbackConfigurer.initLogging(sc);
} catch (BeansException e) {
//不做任何处理
}
}
}
}
2.spring-dubbo.xml 增加节点配置
<bean id="esConfig" class="com.dangdang.config.service.zookeeper.ZookeeperConfigGroup" c:configProfile-ref="configProfile" c:node="es" />
3.将logback里面配置改为参数(KAFKA.SERVER 原先为固定值)
<!--bootstrap.servers 为kafka 部署地址-->
<producerConfig>bootstrap.servers=${KAFKA.SERVER}</producerConfig>