com.zoi7.component.logback.zookeeper.LevelWatcher Maven / Gradle / Ivy
The newest version!
package com.zoi7.component.logback.zookeeper;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.zoi7.component.core.base.BaseClass;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import static com.zoi7.component.logback.zookeeper.LogbackRunner.ZK_LOGBACK_ROOT;
/**
* @author yjy
* 2018-11-02 10:35
*/
public class LevelWatcher extends BaseClass implements Watcher {
private static final Logger log = LoggerFactory.getLogger(LevelWatcher.class);
private static final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
private ZooKeeper zooKeeper;
public LevelWatcher(ZooKeeper zooKeeper) {
this.zooKeeper = zooKeeper;
}
@Override
public void process(WatchedEvent event) {
String rootPath = ZK_LOGBACK_ROOT;
if (rootPath.equals(event.getPath()) && Event.EventType.NodeDataChanged == event.getType()) {
try {
// 从日志配置节点获取所有子节点
List children = zooKeeper.getChildren(rootPath, false);
for (String name : children) {
// 节点路径
String path = rootPath + "/" + name;
// 节点数据(日志等级)
byte[] data = zooKeeper.getData(path, false, null);
// 修改Logback日志等级配置
setLogbackLevel(name, new String(data));
}
// 再次监听配置节点
zooKeeper.exists(rootPath, this);
} catch (InterruptedException | KeeperException e) {
log.error("LogbackWatcher error", e);
}
}
}
/**
* 修改Logback日志等级配置
* @param name 包名
* @param level 等级
*/
private void setLogbackLevel(String name, String level) {
log.info("change logback level > name: {}, level: {}", name, level);
Level l = notBlank(level) ? Level.valueOf(level) : null;
context.getLogger(name).setLevel(l);
}
}