Small program development tutorial]

"/> Small program development tutorial]

">

Home  >  Article  >  WeChat Applet  >  Let’s talk about the Log system in the mini program and see how to build and use it.

Let’s talk about the Log system in the mini program and see how to build and use it.

青灯夜游
青灯夜游forward
2022-01-21 10:26:206080browse

This article will talk about the Log system in the Mini Program, introduce how to use the Mini Program Log system, and how to build the Mini Program Log system. I hope it will be helpful to everyone!

Let’s talk about the Log system in the mini program and see how to build and use it.

Normally, the logging system is an important part of development.

But for various reasons, it is not common to do log printing and reporting systems in front-end development.
But in some specific cases, the log system often works wonders.

For example, a chat system encountered the following problems:

  • During a voice call, the user cannot hear the sound
  • In instant messaging, user feedback in some scenarios, messages Unable to send
  • In instant messaging, when A replies to B's message, the dialog box does not appear occasionally
  • In instant messaging, after A sends two messages to B in a row, B cannot receive the second message Tip
  • In instant messaging, when sending a voice message, the user thinks that the voice message has been sent, but in fact the recording is still continuing. At this time, the user thought that the network was stuck, and finally found that the voices of himself and other people talking were recorded

. However, the above errors were not reflected in the background interface. Coupled with problems with some users' mobile phone models, the problem is difficult to locate.
If we have log here, we can quickly locate the problematic code.
If it is not a code problem, we will be more confident in replying to the user that it is not a problem with our system.

How to use the Mini Program Log system

The Mini Program side provides two Mini Program Log interfaces:

  • LogManager ( Normal log )
  • RealtimeLogManager ( Real-time log )

The official did not introduce the specific difference between the two. It just emphasizes the real-time nature of Realtime.

In my opinion, the biggest difference between them is:

  • LogManager can make users feel at ease, because LogManager is Problems reported manually by users.
  • RealtimeLogManager is more friendly to developers. It can collect problem information without the user's knowledge and fix the problem without the user being aware of it.

LogManager

The Log log interface provided by the applet, through wx.getLogManager( ) Get the instance.
Note:

  • Save up to 5M of log content. After exceeding 5M, the old log content will be deleted.
  • For Mini Program, users can upload printed logs by using button component’s open-type="feedback".
  • For Mini Games, users can create a button to upload printed logs by using wx.createFeedbackButton.
  • Developers can view related printing logs through the left menu Feedback Management page of the mini program management backend.

Create LogManager instance

You can get the log instance through wx.getLogManager().
Parameters can be passed in brackets { level: 0 | 1 } to decide whether to write the life cycle function of Page, the function under the wx namespace log.

  • 0: Write
  • 1: Do not write
 https://github.com/Kujiale-Mobile/Painter

Use LogManager instance

const logger = wx.getLogManager({ level: 0 })
logger.log({str: 'hello world'}, 'basic log', 100, [1, 2, 3])
logger.info({str: 'hello world'}, 'info log', 100, [1, 2, 3])
logger.debug({str: 'hello world'}, 'debug log', 100, [1, 2, 3])
logger.warn({str: 'hello world'}, 'warn log', 100, [1, 2, 3])

User feedback uploads the log recorded by LogManager

After the log is recorded, the user can log on the profile page of the mini program , click Feedback and Complaints, and click Function Abnormality to upload the log.

Developers handle user feedback and communicate with users

Developers can manage in the mini program background -> User Feedback -> Function Abnormality View user feedback information.
Developers can bind customer service WeChat under Function -> Customer Service. After binding, they can communicate with feedback users through WeChat within 48 hours .

Note: When communication requires user feedback, check: Allow developers to contact me via customer service messages within 48 hours.

RealtimeLogManager

The real-time Log log interface provided by the applet, through wx.getRealtimeLogManager () Get the instance.
Notice:

  • wx.getRealtimeLogManager() 基础库 2.7.1 开始支持
  • 官方给出实时日志每条的容量上限是 5kb
  • 官方对每条日志的定义:在一个页面 onShow -> onHide 之间,会聚合成一条日志上报
  • 开发者可从小程序管理后台: 开发 -> 运维中心 -> 实时日志 进入小程序端日志查询页面

为了定位问题方便,日志是按页面划分的,某一个页面,在onShow到onHide(切换到其它页面、右上角圆点退到后台)之间打的日志,会聚合成一条日志上报,并且在小程序管理后台上可以根据页面路径搜索出该条日志

创建 RealtimeLogManager 实例

你可以通过 wx.getRealtimeLogManager() 获取实时日志实例。

const logger = wx.getRealtimeLogManager()

使用 RealtimeLogManager 实例

const logger = wx.getRealtimeLogManager()
logger.debug({str: 'hello world'}, 'debug log', 100, [1, 2, 3])
logger.info({str: 'hello world'}, 'info log', 100, [1, 2, 3])
logger.error({str: 'hello world'}, 'error log', 100, [1, 2, 3])
logger.warn({str: 'hello world'}, 'warn log', 100, [1, 2, 3])

查看实时日志

与普通日志不同的是,实时日志不再需要用户反馈,可以直接通过以下方式查看实例。

  • 登录小程序后台

  • 通过路径 开发 -> 开发管理 -> 运维中心 -> 实时日志 查看实时日志

如何搭建小程序 Log 日志系统

上面我们知道了小程序的 Log 日志怎么使用,我们当然可以不进行封装直接使用。
但是我们直接使用起来会感觉到十分的别扭,因为这不符合我们程序员单点调用的习惯。

那么接下来让我们对这套 Log 系统进行初步的封装以及全局的方法的日志注入。

后续我会在 github 开放源码,并打包至 npm ,需要的开发者可自行 install 调用。

封装小程序 Log 方法

封装 Log 方法前,我们需要整理该方法需要考虑什么内容:

  • 打印格式:统一打印格式有助于我们更快的定位问题
  • 版本号:方便我们清晰的知道当前用户使用的小程序版本,避免出现旧版本问题在新代码中找不到问题
  • 兼容性:我们需要考虑用户小程序版本不足以支持 getLogManagergetRealtimeLogManager 的情况
  • 类型:我们需要兼容 debuglogerror 类型的 log日志

版本问题

我们需要一个常量用以定义版本号,以便于我们定位出问题的代码版本。
如果遇到版本问题,我们可以更好的引导用户

const VERSION = "1.0.0"
const logger = wx.getLogManager({ level: 0 })

logger.log(VERSION, info)

打印格式

我们可以通过 [version] file | content 的统一格式来更快的定位内容。

const VERSION = "1.0.0"
const logger = wx.getLogManager({ level: 0 })

logger.log(`[${VERSION}] ${file} | `, ...args)

兼容性

我们需要考虑用户小程序版本不足以支持 getLogManagergetRealtimeLogManager 的情况

const VERSION = "0.0.18";

const canIUseLogManage = wx.canIUse("getLogManager");
const logger = canIUseLogManage ? wx.getLogManager({ level: 0 }) : null;
const realtimeLogger = wx.getRealtimeLogManager ? wx.getRealtimeLogManager() : null;

export function RUN(file, ...args) {
  console.log(`[${VERSION}]`, file, " | ", ...args);
  if (canIUseLogManage) {
    logger.log(`[${VERSION}]`, file, " | ", ...args);
  }

  realtimeLogger && realtimeLogger.info(`[${VERSION}]`, file, " | ", ...args);
}

类型

我们需要兼容 debuglogerror 类型的 log日志

export function RUN(file, ...args) {
    ...
}

export function DEBUG(file, ...args) {
    ...
}

export function ERROR(file, ...args) {
    ...
}

export function getLogger(fileName) {
  return {
    DEBUG: function (...args) {
      DEBUG(fileName, ...args)
    },
    RUN: function (...args) {
      RUN(fileName, ...args)
    },
    ERROR: function (...args) {
      ERROR(fileName, ...args)
    }
  }
}

完整代码

以上都做到了,就完成了一套 Log 系统的基本封装。

const VERSION = "0.0.18";

const canIUseLogManage = wx.canIUse("getLogManager");
const logger = canIUseLogManage ? wx.getLogManager({ level: 0 }) : null;
const realtimeLogger = wx.getRealtimeLogManager ? wx.getRealtimeLogManager() : null;

export function DEBUG(file, ...args) {
  console.debug(`[${VERSION}] ${file}  | `, ...args);
  if (canIUseLogManage) {
    logger.debug(`[${VERSION}]`, file, " | ", ...args);
  }

  realtimeLogger && realtimeLogger.info(`[${VERSION}]`, file, " | ", ...args);
}

export function RUN(file, ...args) {
  console.log(`[${VERSION}]`, file, " | ", ...args);
  if (canIUseLogManage) {
    logger.log(`[${VERSION}]`, file, " | ", ...args);
  }

  realtimeLogger && realtimeLogger.info(`[${VERSION}]`, file, " | ", ...args);
}

export function ERROR(file, ...args) {
  console.error(`[${VERSION}]`, file, " | ", ...args);
  if (canIUseLogManage) {
    logger.error(`[${VERSION}]`, file, " | ", ...args);
  }

  realtimeLogger && realtimeLogger.error(`[${VERSION}]`, file, " | ", ...args);
}

export function getLogger(fileName) {
  return {
    DEBUG: function (...args) {
      DEBUG(fileName, ...args)
    },
    RUN: function (...args) {
      RUN(fileName, ...args)
    },
    ERROR: function (...args) {
      ERROR(fileName, ...args)
    }
  }
}

全局注入 Log

通过该章节的名称,我们就可以知道全局注入。
全局注入的意思就是,不通过手动调用的形式,在方法写完后自动注入 log ,你只需要在更细节的地方考虑打印 log 即可。

为什么要全局注入

虽然我们实现了全局 log 的封装,但是很多情况下,一些新同学没有好的打 log 的习惯,尤其是前端同学(我也一样)。
所以我们需要做一个全局注入,以方便我们的代码书写,也避免掉手动打 log 会出现遗漏的问题。

如何进行全局注入

小程序提供了 behaviors 参数,用以让多个页面拥有相同的数据字段和方法。

需要注意的是, page 级别的 behaviors 在 2.9.2 之后开始支持

我们可以通过封装一个通用的 behaviors ,然后在需要 log 的页面进行引入即可。

import * as Log from "./log-test";

export default Behavior({
  definitionFilter(defFields) {
    console.log(defFields);
    Object.keys(defFields.methods || {}).forEach(methodName => {
      const originMethod = defFields.methods[methodName];
      defFields.methods[methodName] = function (ev, ...args) {
        if (ev && ev.target && ev.currentTarget && ev.currentTarget.dataset) {
          Log.RUN(defFields.data.PAGE_NAME, `${methodName} invoke, event dataset = `, ev.currentTarget.dataset, "params = ", ...args);
        } else {
          Log.RUN(defFields.data.PAGE_NAME, `${methodName} invoke, params = `, ev, ...args);
        }
        originMethod.call(this, ev, ...args)
      }
    })
  }
})

总结

连着开发带整理,林林总总的也有了 2000+ 字,耗费了三天的时间,整体感觉还是比较值得的,希望可以带给大家一些帮助。

也希望大家更重视前端的 log 一点。这基于我自身的感觉,尤其是移动端用户。
在很多时候由于 手机型号弱网环境 等导致的问题。
在没有 log 时,找不到问题的着力点,导致问题难以被及时解决。

后续我会在 github 开放源码,并打包至 npm ,开发者后续可自行 install 调用。
后续 源码地址npm安装方法 将会在该页面更新。
开放时间基于大家需求而定。

【相关学习推荐:小程序开发教程

The above is the detailed content of Let’s talk about the Log system in the mini program and see how to build and use it.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete