com.zoi7.component.logback.zookeeper.LogbackService Maven / Gradle / Ivy
The newest version!
package com.zoi7.component.logback.zookeeper;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import com.zoi7.component.core.base.BaseClass;
import com.zoi7.component.core.util.page.Pagination;
import com.zoi7.component.core.util.page.SimplePage;
import com.zoi7.component.zookeeper.ZkUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static com.zoi7.component.logback.zookeeper.LogbackRunner.ZK_LOGBACK_ROOT;
/**
* @author yjy
* 2018-11-02 15:11
*/
@Component
public class LogbackService extends BaseClass {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(LogbackService.class);
private static final LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
/**
* 获取 日志级别列表
* @param name 包名筛选
* @param pageNo 页号
* @param pageSize 条数
* @return
*/
public Pagination findPage(String name, int pageNo, int pageSize) {
List list = loggerContext.getLoggerList();
if (notBlank(name)) {
list = list.stream().filter((logger) -> logger.getName().contains(name)).collect(Collectors.toList());
}
Pagination pagination = new Pagination<>(pageNo, pageSize, list.size());
int startIndex = SimplePage.getStart(pageNo, pageSize);
pagination.setList(new ArrayList<>(list.subList(startIndex, Math.min(startIndex + pageSize, list.size()))));
return pagination;
}
/**
* 修改日志级别
* @param name 包名
* @param level 级别
* @throws IOException e
* @throws KeeperException e
* @throws InterruptedException e
*/
public void changeLevel(String name, String level) throws IOException, KeeperException, InterruptedException {
ZooKeeper zooKeeper = null;
try {
zooKeeper = ZkUtils.getInstance().getZooKeeper();
String path = ZK_LOGBACK_ROOT + "/" + name;
Stat stat = zooKeeper.exists(path, false);
if (stat == null) {
zooKeeper.create(path, level.getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
log.info("createNew node: {}", path);
} else {
zooKeeper.setData(path, level.getBytes(), stat.getVersion());
log.info("updateData node: {}", path);
}
// 更新根节点内容, 表示配置有更新
Stat stat1 = zooKeeper.exists(ZK_LOGBACK_ROOT, false);
zooKeeper.setData(ZK_LOGBACK_ROOT, String.valueOf(System.currentTimeMillis()).getBytes(), stat1.getVersion());
} finally {
if (zooKeeper != null)
zooKeeper.close();
}
}
}