js实现treelog
实现 TreeLog 的基本思路
TreeLog 是一种树形结构的日志记录方式,通常用于展示层级化的日志信息。在 JavaScript 中可以通过递归或迭代的方式实现。
定义 TreeLog 数据结构
TreeLog 通常包含节点信息和子节点列表。以下是一个简单的数据结构定义:
class TreeNode {
constructor(message, level = 0) {
this.message = message;
this.level = level;
this.children = [];
}
addChild(node) {
this.children.push(node);
}
}
实现日志收集功能
创建一个 TreeLog 类来管理整个树形日志:
class TreeLog {
constructor() {
this.root = new TreeNode('Root');
this.currentNode = this.root;
}
log(message) {
const newNode = new TreeNode(message, this.currentNode.level + 1);
this.currentNode.addChild(newNode);
this.currentNode = newNode;
return this;
}
end() {
if (this.currentNode !== this.root) {
this.currentNode = this.currentNode.parent || this.root;
}
return this;
}
}
添加缩进格式化输出
为了使日志输出更具可读性,可以添加格式化方法:
class TreeNode {
// ... 之前的代码
toString(indent = 0) {
let result = ' '.repeat(indent) + `- ${this.message}\n`;
for (const child of this.children) {
result += child.toString(indent + 1);
}
return result;
}
}
class TreeLog {
// ... 之前的代码
toString() {
return this.root.toString();
}
}
使用示例
const logger = new TreeLog();
logger.log('Start process')
.log('Step 1')
.log('Substep 1.1').end()
.log('Substep 1.2').end()
.end()
.log('Step 2');
console.log(logger.toString());
高级功能扩展
可以添加时间戳、日志级别等额外信息:
class TreeNode {
constructor(message, level = 0, timestamp = new Date()) {
this.message = message;
this.level = level;
this.timestamp = timestamp;
this.children = [];
}
// ... 其他方法
}
浏览器控制台友好输出
对于浏览器环境,可以重写 toString 方法使用 console.group:
class TreeNode {
printToConsole() {
console.group(`${this.message} (${this.timestamp.toISOString()})`);
this.children.forEach(child => child.printToConsole());
console.groupEnd();
}
}
性能考虑
对于大量日志,可以考虑使用懒加载或分块渲染技术,避免一次性处理过多节点导致性能问题。







