feat(error-report): 接入 index.uploadClientErrorLog - 运行时异常/扫码链路异常自动批量上报(幂等+限流+持久化队列+面板手动上报)
This commit is contained in:
parent
7b3e6f1f79
commit
ffd42fca33
@ -1,5 +1,6 @@
|
||||
<script>
|
||||
import { guardCurrentPage } from './core/nav-guard'
|
||||
import { flushClientErrorReport } from './core/error-report'
|
||||
// rem 基准:以 1920×1280 设计稿为准,100px = 1rem,按宽高取小(contain)缩放
|
||||
const DESIGN_WIDTH = 1920
|
||||
const DESIGN_HEIGHT = 1280
|
||||
@ -107,6 +108,8 @@ export default {
|
||||
},
|
||||
onHide: function () {
|
||||
console.log('App Hide')
|
||||
// 退到后台立即把待上报的错误日志发出去(后台可能被系统回收,晚发就没了)
|
||||
flushClientErrorReport()
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
@ -19,6 +19,26 @@ export function getLoginWechatCode(
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 上报客户端错误日志(免登录、免权限、免鉴权,服务端写 wms_client_error_log)
|
||||
* - 入参支持单条对象/数组/{logs:[...]} 三种形态,单次最多 50 条;这里统一用 { logs } 包裹
|
||||
* - error_message 与 error_stack 至少一项有值;report_uuid 幂等去重(重复上报静默成功)
|
||||
*/
|
||||
export function uploadClientErrorLog(
|
||||
logs: Record<string, unknown>[] | Record<string, unknown>,
|
||||
options?: RequestOptions
|
||||
) {
|
||||
const list = Array.isArray(logs) ? logs : [logs]
|
||||
return request<ApiBody>(
|
||||
'index.uploadClientErrorLog',
|
||||
{ logs: list },
|
||||
{
|
||||
skipAuth: true,
|
||||
...options,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 工作台登录:获取工作台绑定码 / 绑定状态(免登录、免鉴权)
|
||||
* - 不传 clientCode:分配新客户端编码并立即返回绑定码
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
<text class="diag-title">扫码诊断</text>
|
||||
<view class="diag-head-actions">
|
||||
<text class="diag-action" @click="refresh">刷新</text>
|
||||
<text class="diag-action" @click="submitReport">上报</text>
|
||||
<text class="diag-action" @click="copyText">复制</text>
|
||||
<text class="diag-action diag-action--danger" @click="clearLog">清空</text>
|
||||
<text class="diag-action diag-action--close" @click="handleClose">×</text>
|
||||
@ -22,6 +23,7 @@
|
||||
|
||||
<script>
|
||||
import { diagText, diagClear } from '@/core/scan-diag'
|
||||
import { reportScanDiagNow, getClientErrorQueueSize } from '@/core/error-report'
|
||||
|
||||
/**
|
||||
* 扫码诊断面板(现场可读,无需 adb)
|
||||
@ -72,10 +74,22 @@ export default {
|
||||
refresh() {
|
||||
try {
|
||||
this.text = diagText()
|
||||
this.hint = `待上报 ${getClientErrorQueueSize()} 条(点「上报」立即送服务端);真机也可用 adb logcat -s WMSScan`
|
||||
} catch (e) {
|
||||
this.text = `诊断信息生成失败:${e && e.message}`
|
||||
}
|
||||
},
|
||||
/** 手动上报到服务端 wms_client_error_log(带完整扫码诊断快照) */
|
||||
submitReport() {
|
||||
let ok = false
|
||||
try {
|
||||
ok = reportScanDiagNow('诊断面板手动上报')
|
||||
} catch (e) {
|
||||
ok = false
|
||||
}
|
||||
uni.showToast({ title: ok ? '已上报(后台发送)' : '上报被限流,稍后再试', icon: 'none' })
|
||||
this.refresh()
|
||||
},
|
||||
copyText() {
|
||||
try {
|
||||
uni.setClipboardData({
|
||||
|
||||
515
src/core/error-report.js
Normal file
515
src/core/error-report.js
Normal file
@ -0,0 +1,515 @@
|
||||
/**
|
||||
* 客户端错误 / 扫码诊断日志上报(index.uploadClientErrorLog,免登录免鉴权)
|
||||
*
|
||||
* 目标:现场"长时间使用后扫码没反应"这类问题无法复现、也没法现场抓 adb,
|
||||
* 因此把运行时错误与扫码链路异常**自动**批量上报到服务端 wms_client_error_log,
|
||||
* 由服务端按 device_id / error_type 聚合排查。
|
||||
*
|
||||
* 上报内容:
|
||||
* 1. 运行时错误:Vue 渲染/生命周期异常、window error/unhandledrejection、uni 未处理 Promise;
|
||||
* 2. 扫码链路异常(由 scan-diag 通过 setDiagSink 外送):
|
||||
* scan-stall(主线程卡顿)/ scan-heal(自愈动作)/ scan-drop(扫码被丢弃,带收到的码);
|
||||
* 3. 现场手动上报(诊断面板「上报」按钮):scan-manual,带完整精简快照。
|
||||
*
|
||||
* 设计约束(务必保持):
|
||||
* - 任何异常都不得向上抛,绝不能因为上报失败影响业务;
|
||||
* - 批量 ≤50 条/次(接口上限),队列持久化,重启后续报;report_uuid 幂等,重发不会产生重复行;
|
||||
* - 多重限流:同类消息 60s 去重、每会话最多 40 次请求、失败保留队列下次再发;
|
||||
* - 可在现场关闭:uni.setStorageSync('clientErrorLog:disabled', 1)。
|
||||
*/
|
||||
|
||||
import { uploadClientErrorLog } from '@/api/index'
|
||||
import { appEnv } from '@/config/env'
|
||||
import { diagDigest, setDiagSink } from '@/core/scan-diag'
|
||||
|
||||
const STORAGE_QUEUE_KEY = 'clientErrorLog:queue'
|
||||
const STORAGE_DEVICE_KEY = 'clientErrorLog:deviceId'
|
||||
const STORAGE_DISABLED_KEY = 'clientErrorLog:disabled'
|
||||
|
||||
const MAX_BATCH = 50
|
||||
const QUEUE_LIMIT = 200
|
||||
const FLUSH_INTERVAL_MS = 15000
|
||||
const FLUSH_THRESHOLD = 8
|
||||
const RETRY_BASE_DELAY_MS = 5000
|
||||
const MAX_REQUESTS_PER_SESSION = 40
|
||||
const DEDUPE_WINDOW_MS = 60000
|
||||
// 接口侧限制:error_message 5000、error_stack/extra 65535,这里留出余量
|
||||
const MAX_MESSAGE_LEN = 4800
|
||||
const MAX_STACK_LEN = 20000
|
||||
const MAX_EXTRA_LEN = 60000
|
||||
const DIAG_EXTRA_MAX_EVENTS = 30
|
||||
|
||||
let queue = []
|
||||
let installed = false
|
||||
let sending = false
|
||||
let requestCount = 0
|
||||
let consecutiveFailures = 0
|
||||
let flushTimer = null
|
||||
let deviceInfo = null
|
||||
let lastResult = null
|
||||
const lastReportAtByKey = {}
|
||||
|
||||
// ---------- 基础工具(全部 try/catch 包裹,永不抛错) ----------
|
||||
|
||||
function storageGet(key) {
|
||||
try {
|
||||
return uni.getStorageSync(key)
|
||||
} catch (e) {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function storageSet(key, value) {
|
||||
try {
|
||||
uni.setStorageSync(key, value)
|
||||
} catch (e) {
|
||||
// 忽略:存储失败不影响上报流程
|
||||
}
|
||||
}
|
||||
|
||||
function truncate(text, max) {
|
||||
const str = String(text == null ? '' : text)
|
||||
return str.length > max ? str.slice(0, max) : str
|
||||
}
|
||||
|
||||
function isDisabled() {
|
||||
return !!storageGet(STORAGE_DISABLED_KEY)
|
||||
}
|
||||
|
||||
function currentRoute() {
|
||||
try {
|
||||
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
|
||||
const top = pages && pages.length ? pages[pages.length - 1] : null
|
||||
return top && top.route ? String(top.route) : ''
|
||||
} catch (e) {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function deviceId() {
|
||||
let id = String(storageGet(STORAGE_DEVICE_KEY) || '')
|
||||
if (!id) {
|
||||
id = `ws-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
|
||||
storageSet(STORAGE_DEVICE_KEY, id)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
/** 设备信息(首次调用时取一次并缓存) */
|
||||
function resolveDeviceInfo() {
|
||||
if (deviceInfo) {
|
||||
return deviceInfo
|
||||
}
|
||||
let info = {}
|
||||
try {
|
||||
info = (typeof uni !== 'undefined' && uni.getSystemInfoSync && uni.getSystemInfoSync()) || {}
|
||||
} catch (e) {
|
||||
info = {}
|
||||
}
|
||||
const platform = String(info.platform || '').toLowerCase()
|
||||
deviceInfo = {
|
||||
client_type: appEnv.isApp ? 'android' : appEnv.isElectron ? 'electron' : platform || 'web',
|
||||
device_id: deviceId(),
|
||||
os_version: truncate(info.system || info.osVersion || '', 64),
|
||||
device_model: truncate(
|
||||
[info.brand, info.model].filter(Boolean).join(' ') || info.deviceModel || '',
|
||||
128
|
||||
),
|
||||
}
|
||||
return deviceInfo
|
||||
}
|
||||
|
||||
function buildReportUuid() {
|
||||
return `client-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
|
||||
}
|
||||
|
||||
function normalizeExtra(extra) {
|
||||
let text = ''
|
||||
try {
|
||||
text = typeof extra === 'string' ? extra : JSON.stringify(extra == null ? {} : extra)
|
||||
} catch (e) {
|
||||
text = String(extra)
|
||||
}
|
||||
return truncate(text, MAX_EXTRA_LEN)
|
||||
}
|
||||
|
||||
// ---------- 队列 ----------
|
||||
|
||||
function persistQueue() {
|
||||
storageSet(STORAGE_QUEUE_KEY, queue.slice(-QUEUE_LIMIT))
|
||||
}
|
||||
|
||||
function loadQueue() {
|
||||
const cached = storageGet(STORAGE_QUEUE_KEY)
|
||||
if (Array.isArray(cached)) {
|
||||
queue = cached.filter((item) => item && typeof item === 'object').slice(-QUEUE_LIMIT)
|
||||
}
|
||||
}
|
||||
|
||||
function enqueue(log) {
|
||||
queue.push(log)
|
||||
if (queue.length > QUEUE_LIMIT) {
|
||||
queue.splice(0, queue.length - QUEUE_LIMIT)
|
||||
}
|
||||
persistQueue()
|
||||
if (queue.length >= FLUSH_THRESHOLD) {
|
||||
scheduleFlush(300)
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleFlush(delay) {
|
||||
if (flushTimer || isDisabled()) {
|
||||
return
|
||||
}
|
||||
flushTimer = setTimeout(() => {
|
||||
flushTimer = null
|
||||
flushClientErrorReport()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
/**
|
||||
* 立即上报一批(公开给页面/面板调用)。
|
||||
* 返回 Promise,但调用方可以不管;内部失败只保留队列,不抛错。
|
||||
*/
|
||||
export async function flushClientErrorReport() {
|
||||
if (sending || isDisabled()) {
|
||||
return
|
||||
}
|
||||
if (!queue.length) {
|
||||
scheduleFlush(FLUSH_INTERVAL_MS)
|
||||
return
|
||||
}
|
||||
if (requestCount >= MAX_REQUESTS_PER_SESSION) {
|
||||
return
|
||||
}
|
||||
|
||||
sending = true
|
||||
const batch = queue.slice(0, MAX_BATCH)
|
||||
try {
|
||||
const body = await uploadClientErrorLog(batch, { timeout: 20000 })
|
||||
const code = Number(body && body.code)
|
||||
const ok = body && (body.flag === 'success' || code === 200 || body.success === true)
|
||||
lastResult = {
|
||||
at: Date.now(),
|
||||
batch: batch.length,
|
||||
flag: body && body.flag,
|
||||
code,
|
||||
message: (body && body.message) || '',
|
||||
accepted: body && body.accepted,
|
||||
duplicated: body && body.duplicated,
|
||||
rejected: body && body.rejected,
|
||||
}
|
||||
if (ok) {
|
||||
queue.splice(0, batch.length)
|
||||
persistQueue()
|
||||
requestCount += 1
|
||||
consecutiveFailures = 0
|
||||
} else if (code === 400) {
|
||||
// 入参/数据问题:这批永远发不出去,丢弃以免阻塞后续日志
|
||||
queue.splice(0, batch.length)
|
||||
persistQueue()
|
||||
requestCount += 1
|
||||
} else {
|
||||
consecutiveFailures += 1
|
||||
}
|
||||
} catch (e) {
|
||||
// 网络异常:保留队列,退避后重试
|
||||
consecutiveFailures += 1
|
||||
lastResult = { at: Date.now(), batch: batch.length, error: (e && e.message) || 'network-error' }
|
||||
} finally {
|
||||
sending = false
|
||||
if (queue.length) {
|
||||
const delay = Math.min(
|
||||
RETRY_BASE_DELAY_MS * Math.pow(2, Math.min(consecutiveFailures, 4)),
|
||||
5 * 60 * 1000
|
||||
)
|
||||
scheduleFlush(consecutiveFailures > 0 ? delay : FLUSH_INTERVAL_MS)
|
||||
} else if (!flushTimer) {
|
||||
scheduleFlush(FLUSH_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 上报入口 ----------
|
||||
|
||||
/**
|
||||
* 上报一条错误/诊断日志。
|
||||
* @param payload { type, message, stack, extra, force }
|
||||
* @returns boolean 是否进入队列(被限流/关闭时返回 false)
|
||||
*/
|
||||
export function reportClientError(payload = {}) {
|
||||
try {
|
||||
if (isDisabled()) {
|
||||
return false
|
||||
}
|
||||
const message = truncate(payload.message, MAX_MESSAGE_LEN)
|
||||
const stack = truncate(payload.stack, MAX_STACK_LEN)
|
||||
if (!message && !stack) {
|
||||
return false
|
||||
}
|
||||
const type = String(payload.type || 'error')
|
||||
// 同类消息 60s 去重:避免同一异常刷爆服务端(force 可绕过,如现场手动上报)
|
||||
const dedupeKey = `${type}|${message}`
|
||||
const now = Date.now()
|
||||
if (
|
||||
!payload.force &&
|
||||
lastReportAtByKey[dedupeKey] &&
|
||||
now - lastReportAtByKey[dedupeKey] < DEDUPE_WINDOW_MS
|
||||
) {
|
||||
return false
|
||||
}
|
||||
lastReportAtByKey[dedupeKey] = now
|
||||
|
||||
const info = resolveDeviceInfo()
|
||||
enqueue({
|
||||
client_type: info.client_type,
|
||||
device_id: info.device_id,
|
||||
os_version: info.os_version,
|
||||
device_model: info.device_model,
|
||||
app_version: appEnv.version,
|
||||
error_type: type,
|
||||
error_message: message,
|
||||
error_stack: stack,
|
||||
extra: normalizeExtra(
|
||||
Object.assign({ route: currentRoute(), packType: appEnv.packType }, payload.extra || {})
|
||||
),
|
||||
report_uuid: buildReportUuid(),
|
||||
client_time: now,
|
||||
})
|
||||
return true
|
||||
} catch (e) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 现场手动上报:带完整扫码诊断快照(面板「上报」按钮用) */
|
||||
export function reportScanDiagNow(reason = '手动上报') {
|
||||
const ok = reportClientError({
|
||||
type: 'scan-manual',
|
||||
message: `扫码诊断手动上报:${reason}`,
|
||||
extra: { diag: diagDigest(60) },
|
||||
force: true,
|
||||
})
|
||||
flushClientErrorReport()
|
||||
return ok
|
||||
}
|
||||
|
||||
// ---------- 扫码诊断外送 ----------
|
||||
|
||||
function hookDiagSink() {
|
||||
setDiagSink((kind, payload) => {
|
||||
try {
|
||||
if (kind === 'stall') {
|
||||
// 消息文本保持稳定(不带变化量)以便 60s 去重,细节放 extra
|
||||
reportClientError({
|
||||
type: 'scan-stall',
|
||||
message: '扫码期间主线程卡顿',
|
||||
extra: { stall: payload, diag: diagDigest(DIAG_EXTRA_MAX_EVENTS) },
|
||||
})
|
||||
return
|
||||
}
|
||||
if (kind === 'heal') {
|
||||
reportClientError({
|
||||
type: 'scan-heal',
|
||||
message: `扫码链路自愈:${payload.reason}`,
|
||||
extra: { heal: payload.data || {}, diag: diagDigest(DIAG_EXTRA_MAX_EVENTS) },
|
||||
})
|
||||
return
|
||||
}
|
||||
if (kind === 'drop') {
|
||||
const data = payload.data || {}
|
||||
// 同样保持消息稳定:reason 相同则 60s 内只上报一条,累计次数在 extra.drop.count
|
||||
reportClientError({
|
||||
type: 'scan-drop',
|
||||
message: `扫码被丢弃:${payload.reason}`,
|
||||
extra: {
|
||||
drop: { reason: payload.reason, count: payload.count, ...data },
|
||||
diag: diagDigest(DIAG_EXTRA_MAX_EVENTS),
|
||||
},
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略:上报失败不影响扫码
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- 全局错误钩子 ----------
|
||||
|
||||
function describeUnknown(value) {
|
||||
if (value instanceof Error) {
|
||||
return { message: value.message || String(value), stack: value.stack || '' }
|
||||
}
|
||||
if (value && typeof value === 'object') {
|
||||
try {
|
||||
return { message: value.message ? String(value.message) : JSON.stringify(value), stack: value.stack || '' }
|
||||
} catch (e) {
|
||||
return { message: String(value), stack: '' }
|
||||
}
|
||||
}
|
||||
return { message: String(value == null ? '' : value), stack: '' }
|
||||
}
|
||||
|
||||
function hookGlobalErrors(vueApp) {
|
||||
// 1) Vue 渲染 / 生命周期 / 事件处理异常
|
||||
try {
|
||||
if (vueApp && vueApp.config) {
|
||||
const previous = vueApp.config.errorHandler
|
||||
vueApp.config.errorHandler = (err, instance, info) => {
|
||||
const desc = describeUnknown(err)
|
||||
reportClientError({
|
||||
type: 'vue-error',
|
||||
message: `[${info || 'vue'}] ${desc.message}`,
|
||||
stack: desc.stack,
|
||||
extra: { hook: info || '' },
|
||||
})
|
||||
if (typeof previous === 'function') {
|
||||
try {
|
||||
previous(err, instance, info)
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
// 2) 全局 JS 错误与未处理 Promise(H5/Electron 及部分 App WebView 有 window)
|
||||
try {
|
||||
if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
|
||||
window.addEventListener('error', (event) => {
|
||||
const desc = describeUnknown((event && (event.error || event.message)) || '')
|
||||
reportClientError({
|
||||
type: 'window-error',
|
||||
message: desc.message,
|
||||
stack: desc.stack,
|
||||
extra: {
|
||||
source: (event && event.filename) || '',
|
||||
line: (event && event.lineno) || '',
|
||||
column: (event && event.colno) || '',
|
||||
},
|
||||
})
|
||||
})
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
const desc = describeUnknown(event && event.reason)
|
||||
reportClientError({
|
||||
type: 'unhandled-rejection',
|
||||
message: desc.message,
|
||||
stack: desc.stack,
|
||||
})
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
// 3) uni 未处理 Promise(存在则挂载)
|
||||
try {
|
||||
if (typeof uni !== 'undefined' && typeof uni.onUnhandledRejection === 'function') {
|
||||
uni.onUnhandledRejection((res) => {
|
||||
const desc = describeUnknown(res && res.reason)
|
||||
reportClientError({
|
||||
type: 'uni-unhandled-rejection',
|
||||
message: desc.message,
|
||||
stack: desc.stack,
|
||||
})
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
|
||||
// 4) uni 全局错误(部分平台提供 onError,存在则挂载)
|
||||
try {
|
||||
if (typeof uni !== 'undefined' && typeof uni.onError === 'function') {
|
||||
uni.onError((error) => {
|
||||
const desc = describeUnknown(error)
|
||||
reportClientError({
|
||||
type: 'uni-error',
|
||||
message: desc.message,
|
||||
stack: desc.stack,
|
||||
})
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装上报(main.js 创建 app 后调用一次)
|
||||
* @param vueApp createSSRApp 返回的 app 实例(用于挂 Vue errorHandler)
|
||||
*/
|
||||
export function installClientErrorReport(vueApp) {
|
||||
if (installed) {
|
||||
return
|
||||
}
|
||||
installed = true
|
||||
try {
|
||||
loadQueue()
|
||||
hookDiagSink()
|
||||
hookGlobalErrors(vueApp)
|
||||
exposeDebugApi()
|
||||
scheduleFlush(FLUSH_INTERVAL_MS)
|
||||
// 上一次运行残留的日志(崩溃/杀进程前没发出去)优先发一批
|
||||
if (queue.length) {
|
||||
scheduleFlush(3000)
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略:上报不可用不影响应用启动
|
||||
}
|
||||
}
|
||||
|
||||
/** 现场关闭/开启上报(调试用;关闭后队列保留不再发送) */
|
||||
export function setClientErrorReportEnabled(enabled) {
|
||||
if (enabled) {
|
||||
try {
|
||||
uni.removeStorageSync(STORAGE_DISABLED_KEY)
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
scheduleFlush(0)
|
||||
return
|
||||
}
|
||||
storageSet(STORAGE_DISABLED_KEY, 1)
|
||||
}
|
||||
|
||||
/** 当前队列长度(诊断面板展示用) */
|
||||
export function getClientErrorQueueSize() {
|
||||
return queue.length
|
||||
}
|
||||
|
||||
/** 上报模块状态(联调/现场排查用) */
|
||||
export function getClientErrorReportState() {
|
||||
return {
|
||||
queue: queue.length,
|
||||
requestCount,
|
||||
consecutiveFailures,
|
||||
disabled: isDisabled(),
|
||||
lastResult,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* H5/Electron 暴露调试入口(App 逻辑层无 window,自动跳过):
|
||||
* 控制台可用 window.__wmsErrorReport.state() 看队列与服务端应答
|
||||
*/
|
||||
function exposeDebugApi() {
|
||||
try {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
window.__wmsErrorReport = {
|
||||
report: reportClientError,
|
||||
reportDiag: reportScanDiagNow,
|
||||
flush: flushClientErrorReport,
|
||||
state: getClientErrorReportState,
|
||||
enable: () => setClientErrorReportEnabled(true),
|
||||
disable: () => setClientErrorReportEnabled(false),
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
@ -61,6 +61,29 @@ const state = {
|
||||
|
||||
// ---------- 基础工具 ----------
|
||||
|
||||
/**
|
||||
* 诊断事件外送上钩子:由 src/core/error-report.js 注册。
|
||||
* 只在"异常类"事件上触发(卡顿/自愈/带内容的丢弃),让服务端能远程看到现场异常,
|
||||
* 而不需要现场人员打开面板。这里用回调而非直接 import,避免两个模块循环依赖。
|
||||
*/
|
||||
let sink = null
|
||||
|
||||
/** 注册外送上钩子(fn(kind, payload));传 null 取消 */
|
||||
export function setDiagSink(fn) {
|
||||
sink = typeof fn === 'function' ? fn : null
|
||||
}
|
||||
|
||||
function emitSink(kind, payload) {
|
||||
if (!sink) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
sink(kind, payload)
|
||||
} catch (e) {
|
||||
// 上报失败绝不影响业务
|
||||
}
|
||||
}
|
||||
|
||||
function hasUni() {
|
||||
return typeof uni !== 'undefined' && !!uni && typeof uni.setStorageSync === 'function'
|
||||
}
|
||||
@ -316,6 +339,9 @@ export function diagDrop(reason, data) {
|
||||
if (count === 1 || now - last >= minInterval || count % 100 === 0) {
|
||||
state.dropLoggedAt[key] = now
|
||||
push('drop', `reason=${key} count=${count}`, data)
|
||||
if (hasContent) {
|
||||
emitSink('drop', { reason: key, count, data })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -329,6 +355,7 @@ export function diagFlush(info) {
|
||||
export function diagHeal(reason, data) {
|
||||
state.counters.heals += 1
|
||||
push('heal', `reason=${reason} count=${state.counters.heals}`, data)
|
||||
emitSink('heal', { reason, data })
|
||||
}
|
||||
|
||||
/** 记录任意备注(生命周期、提交动作、状态切换等) */
|
||||
@ -376,6 +403,7 @@ export function diagHeartbeat(options) {
|
||||
keys: state.counters.keys,
|
||||
gates: state.gates,
|
||||
})
|
||||
emitSink('stall', { gapMs: tickGap, intervalMs, keys: state.counters.keys, gates: state.gates })
|
||||
}
|
||||
if (!opts.force && now - state.lastHealthAt < HEALTH_INTERVAL_MS) {
|
||||
return
|
||||
@ -426,6 +454,22 @@ export function diagSnapshot() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 精简快照(上报服务端用:带上下文与最近事件,体积可控) */
|
||||
export function diagDigest(maxEvents = 25) {
|
||||
const snapshot = diagSnapshot()
|
||||
return {
|
||||
scope: snapshot.scope,
|
||||
uptimeMs: snapshot.uptimeMs,
|
||||
counters: snapshot.counters,
|
||||
gates: snapshot.gates,
|
||||
context: snapshot.context,
|
||||
lastKeyAgoMs: snapshot.lastKeyAgoMs,
|
||||
stallCount: snapshot.stallCount,
|
||||
maxTickGapMs: snapshot.maxTickGapMs,
|
||||
events: snapshot.events.slice(-maxEvents),
|
||||
}
|
||||
}
|
||||
|
||||
/** 纯文本摘要(现场截图/复制即可上报,无需 adb) */
|
||||
export function diagText() {
|
||||
const snapshot = diagSnapshot()
|
||||
|
||||
@ -4,6 +4,7 @@ import {
|
||||
import App from "./App.vue";
|
||||
import appEnv from './config/env'
|
||||
import { installNavGuard } from './core/nav-guard'
|
||||
import { installClientErrorReport } from './core/error-report'
|
||||
import { getVoice } from './core/voice'
|
||||
|
||||
// #ifdef APP-PLUS
|
||||
@ -75,6 +76,8 @@ export function createApp() {
|
||||
app.provide('appEnv', appEnv)
|
||||
// 路由前置守卫:必须在任何页面跳转发生前安装
|
||||
installNavGuard()
|
||||
// 客户端错误/扫码诊断日志上报(index.uploadClientErrorLog,免登录免鉴权)
|
||||
installClientErrorReport(app)
|
||||
return {
|
||||
app,
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user