【封装小程序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 };
相关推荐
weixin_lynhgworld10 小时前
盲盒抽谷机小程序系统开发:从0到1的完整方法论
小程序
weixin_lynhgworld10 小时前
短剧小程序系统开发:赋能创作者,推动短剧艺术创新发展
小程序
一匹电信狗13 小时前
【C++】异常详解(万字解读)
服务器·c++·算法·leetcode·小程序·stl·visual studio
说私域21 小时前
基于开源AI智能客服、AI智能名片与S2B2C商城小程序的微商服务优化及复购转介绍提升策略研究
人工智能·小程序
熬耶1 天前
Uniapp之微信小程序自定义底部导航栏形态
微信小程序·小程序·uni-app
IT毕设实战小研2 天前
基于Spring Boot校园二手交易平台系统设计与实现 二手交易系统 交易平台小程序
java·数据库·vue.js·spring boot·后端·小程序·课程设计
weixin_177297220692 天前
剧本杀小程序系统开发:重构推理娱乐生态
小程序·重构·娱乐
IT毕设实战小研2 天前
基于SpringBoot的救援物资管理系统 受灾应急物资管理系统 物资管理小程序
java·开发语言·vue.js·spring boot·小程序·毕业设计·课程设计
程序员陆通3 天前
零基础AI编程开发微信小程序赚流量主广告实战
微信小程序·小程序·ai编程
paopaokaka_luck3 天前
校园快递小程序(腾讯地图API、二维码识别、Echarts图形化分析)
vue.js·spring boot·后端·小程序·uni-app