BaseBackend.js 1.73 KB
/**
 * 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 };