【封装小程序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 };
相关推荐
云起SAAS9 分钟前
ai周公解梦抖音快手微信小程序看广告流量主开源
微信小程序·小程序·ai编程·看广告变现轻·ai周公解梦
Jing_jing_X2 小时前
微信小程序开发踩坑记:从AI工具翻车到找到合适方案
人工智能·ai·小程序·产品运营·个人开发
一匹电信狗3 小时前
【MySQL】数据库的相关操作
linux·运维·服务器·数据库·mysql·ubuntu·小程序
weixin_lynhgworld8 小时前
旧物新生,从二手回收小程序开启绿色生活
小程序·生活·旧物回收
從南走到北9 小时前
智尚招聘求职小程序v1.0.23
微信小程序·小程序
2501_9159184113 小时前
掌握 iOS 26 App 运行状况,多工具协作下的监控策略
android·ios·小程序·https·uni-app·iphone·webview
知识分享小能手14 小时前
uni-app 入门学习教程,从入门到精通,uni-app基础扩展 —— 详细知识点与案例(3)
vue.js·学习·ui·微信小程序·小程序·uni-app·编程
2501_9159090616 小时前
iOS 混淆实战,多工具组合完成 IPA 混淆与加固(源码 + 成品 + 运维一体化方案)
android·运维·ios·小程序·uni-app·iphone·webview
狂团商城小师妹16 小时前
智尚房产中介小程序
微信小程序·小程序
狂团商城小师妹20 小时前
预约洗车小程序
微信小程序·小程序