BaseBackend.js
1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* BaseBackend - 日志后端基类
*
* 所有日志存储后端必须继承此类并实现其抽象方法
*/
class BaseBackend {
constructor(options = {}) {
this.name = options.name || 'base';
this.level = options.level || 'info';
this.enabled = options.enabled !== false;
this.categories = options.categories || ['*']; // ['agent', 'protocol', 'tool', 'file', 'system']
}
/**
* 初始化后端
*/
async init() {
throw new Error('init() must be implemented by subclass');
}
/**
* 写入日志条目
* @param {Object} entry - 日志条目
*/
async write(entry) {
throw new Error('write() must be implemented by subclass');
}
/**
* 批量写入
* @param {Object[]} entries - 日志条目数组
*/
async writeBatch(entries) {
for (const entry of entries) {
await this.write(entry);
}
}
/**
* 查询日志
* @param {Object} filters - 查询条件
*/
async query(filters = {}) {
throw new Error('query() must be implemented by subclass');
}
/**
* 关闭后端
*/
async close() {
// 子类可选实现
}
/**
* 检查是否应该记录该条目
* @protected
*/
_shouldLog(entry) {
if (!this.enabled) return false;
// 检查级别
const levels = { debug: 0, info: 1, warn: 2, error: 3, fatal: 4 };
if (levels[entry.level] < levels[this.level]) return false;
// 检查分类
if (!this.categories.includes('*') && !this.categories.includes(entry.category)) {
return false;
}
return true;
}
/**
* 格式化日志条目
* @protected
*/
_formatEntry(entry) {
return {
timestamp: new Date().toISOString(),
...entry
};
}
}
module.exports = { BaseBackend };