【封装小程序log,设定层级】

javascript 复制代码
// utils/logger.js
const log = wx.getRealtimeLogManager ? wx.getRealtimeLogManager() : null; // 手机端点击投诉可以在平台看到日志

const levels = {
  DEBUG: 'debug', // 开发和调试阶段使用
  INFO: 'info', // 记录程序正常运行情况
  WARN: 'warn', // 记录程序运行出现的潜在问题
  ERROR: 'error' // 程序运行过程出现严重错误
};

const prefixes = {
  DEBUG: '[DEBUG]',
  INFO: '[INFO]',
  WARN: '[WARN]',
  ERROR: '[ERROR]'
};

class Logger {
  constructor(level = levels.INFO) {
    this.level = level;
  }

  setLevel(level) {
    this.level = level;
  }

  log(level, ...args) {
    if (this.shouldLog(level)) {
      const timestamp = new Date().toLocaleString();
      const prefix = prefixes[level.toUpperCase()] || '';
      const logMessage = `[${timestamp}] ${prefix} ${args.join(' ')}`;
      console.log(logMessage);
      this.sendToRealtimeLog(level, ...args);
    }
  }

  debug(...args) {
    this.log(levels.DEBUG, ...args);
  }

  info(...args) {
    this.log(levels.INFO, ...args);
  }

  warn(...args) {
    this.log(levels.WARN, ...args);
  }

  error(...args) {
    this.log(levels.ERROR, ...args);
  }

  shouldLog(level) {
    const levelOrder = [levels.DEBUG, levels.INFO, levels.WARN, levels.ERROR];
    return levelOrder.indexOf(level) >= levelOrder.indexOf(this.level);
  }

  sendToRealtimeLog(level, ...args) {
    if (!log) {
      return;
    }
    switch (level) {
      case levels.INFO:
        log.info.apply(log, args);
        break;
      case levels.WARN:
        log.warn.apply(log, args);
        break;
      case levels.ERROR:
        log.error.apply(log, args);
        break;
      default:
        log.debug ? log.debug.apply(log, args) : log.info.apply(log, args);
        break;
    }
  }

  setFilterMsg(msg) {
    if (!log || !log.setFilterMsg) {
      return;
    }
    if (typeof msg !== "string") {
      return;
    }
    log.setFilterMsg(msg);
  }

  addFilterMsg(msg) {
    if (!log || !log.addFilterMsg) {
      return;
    }
    if (typeof msg !== "string") {
      return;
    }
    log.addFilterMsg(msg);
  }
}

const logger = new Logger(levels.DEBUG); // 默认日志级别为 DEBUG

export default logger;
export { levels };
相关推荐
黄华SJ520it3 小时前
顶俏洗衣液模式制度开发介绍:S2B2C社交分销+多门店核销系统全解析
前端·数据库·小程序·零售·系统开发
北极糊的狐6 小时前
钉钉小程序报错data.formatTime is not a function是因为 axml 模板中不能直接调用 Page 内自定义方法!
java·小程序·钉钉
show4331 天前
多格式导出怎么做?2026免费小程序TXT/SRT实践
开发语言·小程序·c#
AI砖家1 天前
AI编程—微信小程序开发规范
微信小程序·小程序·notepad++·ai编程
show4332 天前
2026小程序端视频转文字技术对比:识别引擎精度实测
小程序·音视频
sam-zy2 天前
微信小程序+ESP8266+Arduino 开发智能插座,有本地OTA功能
微信小程序·小程序
A24207349302 天前
微信小程序开发:常用基础语法与指令详解
微信小程序·小程序·notepad++
黄华SJ520it2 天前
青蓝送水类型社交裂变小程序系统技术拆解
小程序·系统开发
weikecms3 天前
星巴克API接口,星巴克点餐接口开发
大数据·小程序
游戏开发爱好者83 天前
系统状态:专为iPhone和iPad设计的实时系统性能监控工具全面介绍
android·ios·小程序·uni-app·iphone·webview·ipad