【封装小程序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 };
相关推荐
一蓑烟雨,一任平生4 小时前
基于 uni-app + <movable-view>拖拽实现的标签排序-适用于微信小程序、H5等多端
微信小程序·小程序·uni-app
UzumakiHan4 小时前
微信小程序一次性订阅封装
微信小程序·小程序
与月儿漫邀10 小时前
二次封装 Vuex for Uniapp 微信小程序开发
微信小程序·小程序·uni-app
夏虫不与冰语11 小时前
uniapp编译小程序,不支持:class语法
小程序·uni-app
专注echarts研发20年12 小时前
微信小程序数据接收
微信小程序·小程序
郑州拽牛科技12 小时前
线下陪玩app小程序 陪玩同城搭子系统开发;
大数据·微信小程序·小程序·系统架构·开源软件
ywyy679814 小时前
短剧看广告APP系统开发:打造高效变现与用户体验双赢平台
大数据·网络·人工智能·小程序·短剧·广告联盟
猫32819 小时前
微信小程序获取手机号
微信小程序·小程序
Minyy111 天前
注册并创建一个微信小程序
微信小程序·小程序
abigale031 天前
微信小程序常用方法
微信小程序·小程序