feat(scan-diag): 日志补日期+毫秒时间戳,记录收到的条码与期望条码上下文

This commit is contained in:
liufumingren 2026-09-25 01:20:19 +08:00
parent 1eb8a1dfe5
commit 7820b29d6e
5 changed files with 170 additions and 20 deletions

View File

@ -23,6 +23,10 @@ const PERSIST_THROTTLE_MS = 2000
const HEALTH_INTERVAL_MS = 60 * 1000
// 同一丢弃原因的最小记录间隔(计数照常累加,避免刷屏)
const DROP_LOG_MIN_INTERVAL_MS = 30 * 1000
// 带内容(收到的条码/已缓冲的字符)的丢弃必须留痕,只用 1s 节流防刷屏
const CONTENT_LOG_MIN_INTERVAL_MS = 1000
// 单个字段值最长保留字符数(超长时截断,避免整条日志被一条条码刷满)
const MAX_VALUE_LEN = 220
// 超过该空闲时长后恢复的第一下按键单独记一条 key-resume
const KEY_RESUME_GAP_MS = 60 * 1000
@ -32,6 +36,8 @@ const state = {
events: [],
counters: { keys: 0, keysBySource: {}, flushes: 0, heals: 0, drops: {} },
gates: {},
// 当前业务上下文(任务号、期望条码…):面板顶部展示 + 随日志落盘
context: {},
prevCounters: null,
lastKeyAt: 0,
lastHealthAt: 0,
@ -60,6 +66,37 @@ function fmtClock(ts) {
return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
}
/**
* 事件时间戳:MM-DD HH:MM:SS.mmm
* 排查"长时间运行"问题时只有时分秒不够用:跨天、以及同一秒内多个事件都区分不出来。
*/
function fmtStamp(ts) {
const d = new Date(ts)
return (
`${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ` +
`${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}.` +
String(d.getMilliseconds()).padStart(3, '0')
)
}
/** 完整日期时间:YYYY-MM-DD HH:MM:SS */
function fmtFull(ts) {
const d = new Date(ts)
return (
`${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ` +
`${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
)
}
/** 应用版本(vite define 注入,取不到就空) */
function appVersion() {
try {
return typeof __APP_VERSION__ !== 'undefined' ? String(__APP_VERSION__) : ''
} catch (e) {
return ''
}
}
function fmtDuration(ms) {
const totalSec = Math.max(0, Math.floor(ms / 1000))
if (totalSec < 60) {
@ -84,8 +121,11 @@ function tidy(data) {
return
}
const type = typeof value
if (type === 'number' || type === 'boolean' || type === 'string') {
if (type === 'number' || type === 'boolean') {
out[key] = value
} else if (type === 'string') {
// 条码内容要留下,但过长时截断
out[key] = value.length > MAX_VALUE_LEN ? `${value.slice(0, MAX_VALUE_LEN)}…` : value
}
})
return Object.keys(out).length ? out : undefined
@ -137,6 +177,7 @@ function persistNow() {
scope: state.scope,
counters: state.counters,
gates: state.gates,
context: state.context,
events: state.events.slice(-MAX_PERSIST_EVENTS),
})
} catch (e) {
@ -169,6 +210,9 @@ function load() {
state.events = raw.events
.filter((item) => item && item.t && item.msg)
.slice(-MAX_PERSIST_EVENTS)
if (raw.context && typeof raw.context === 'object') {
state.context = raw.context
}
if (raw.counters && typeof raw.counters === 'object') {
// 上次运行的累计值仅作参考,不并入本次计数
state.prevCounters = raw.counters
@ -189,7 +233,7 @@ function push(kind, message, data) {
}
// 按键逐条记录会刷屏,只计数(key-resume 会单独 push)
if (kind !== 'key') {
logcat(`${fmtClock(entry.t)} [${kind}] ${entry.msg}`)
logcat(`${fmtStamp(entry.t)} [${kind}] ${entry.msg}`)
schedulePersist()
}
return entry
@ -242,7 +286,14 @@ export function diagDrop(reason, data) {
const count = state.counters.drops[key]
const now = Date.now()
const last = state.dropLoggedAt[key] || 0
if (count === 1 || now - last >= DROP_LOG_MIN_INTERVAL_MS || count % 100 === 0) {
// 带内容(收到的条码 / 已缓冲的字符)的丢弃必须留痕,否则现场无法回答
// “扫的是哪个码、为什么没生效”;纯计数型的丢弃按间隔节流即可
const hasContent = !!(
data &&
((data.code && String(data.code).length) || (data.buffer && String(data.buffer).length))
)
const minInterval = hasContent ? CONTENT_LOG_MIN_INTERVAL_MS : DROP_LOG_MIN_INTERVAL_MS
if (count === 1 || now - last >= minInterval || count % 100 === 0) {
state.dropLoggedAt[key] = now
push('drop', `reason=${key} count=${count}`, data)
}
@ -266,6 +317,23 @@ export function diagNote(name, data) {
push('note', String(name || ''), data)
}
/**
* 设置/更新当前业务上下文(当前任务、期望条码等)。
* 变更时留一条记录:现场看日志时能直接对照“该收到哪个码 / 现在在做什么任务”。
*/
export function diagSetContext(patch) {
load()
const tidyPatch = tidy(patch)
if (!tidyPatch) {
return
}
const before = JSON.stringify(state.context)
state.context = Object.assign({}, state.context, tidyPatch)
if (JSON.stringify(state.context) !== before) {
push('note', 'context', state.context)
}
}
/** 健康心跳:默认 60s 一条,含区间按键数/丢弃增量/门控快照 */
export function diagHeartbeat(force) {
const now = Date.now()
@ -309,6 +377,7 @@ export function diagSnapshot() {
drops: Object.assign({}, state.counters.drops),
},
gates: Object.assign({}, state.gates),
context: Object.assign({}, state.context),
lastKeyAgoMs: state.lastKeyAt ? Date.now() - state.lastKeyAt : null,
events: state.events.slice(),
}
@ -318,9 +387,16 @@ export function diagSnapshot() {
export function diagText() {
const snapshot = diagSnapshot()
const lines = []
const version = appVersion()
lines.push(
`【扫码诊断】scope=${snapshot.scope} 运行=${fmtDuration(snapshot.uptimeMs)} 现在=${fmtClock(Date.now())}`
`【扫码诊断】${fmtFull(Date.now())} scope=${snapshot.scope}` +
`${version ? ` 版本=${version}` : ''} 已运行=${fmtDuration(snapshot.uptimeMs)}`
)
const ctxKeys = Object.keys(snapshot.context)
if (ctxKeys.length) {
// 业务上下文(当前任务 / 期望条码)——“应该接收到的条码”就看这里
lines.push(`上下文 ${ctxKeys.map((key) => `${key}=${snapshot.context[key]}`).join(' ')}`)
}
lines.push(
`按键到达=${snapshot.counters.keys}` +
(snapshot.lastKeyAgoMs === null
@ -338,10 +414,10 @@ export function diagText() {
}`
)
lines.push(`门控快照=${JSON.stringify(snapshot.gates)}`)
lines.push('---- 最近事件(新→旧) ----')
lines.push('---- 最近事件(新→旧,时间=月-日 时:分:秒.毫秒) ----')
const events = snapshot.events
for (let i = events.length - 1; i >= 0 && i >= events.length - 80; i--) {
lines.push(`${fmtClock(events[i].t)} [${events[i].kind}] ${events[i].msg}`)
lines.push(`${fmtStamp(events[i].t)} [${events[i].kind}] ${events[i].msg}`)
}
return lines.join('\n')
}

View File

@ -100,6 +100,14 @@ function resetBuffer() {
lastAt = 0
}
/** 当前已缓冲字符的尾部:丢弃时用它回答"扫的码已经收到多少了" */
function bufferTail(max = 40) {
if (!buffer) {
return ''
}
return buffer.length > max ? buffer.slice(-max) : buffer
}
function flush(trigger, source) {
clearTimer()
const code = buffer.trim()
@ -114,12 +122,13 @@ function flush(trigger, source) {
// 少于最小长度的码直接丢弃(可能是键盘误按/短码)
if (code.length < minLength) {
diagDrop('too-short', { length: code.length, minLength, trigger, source })
diagDrop('too-short', { code, length: code.length, minLength, trigger, source })
debug('code-dropped', { reason: 'too-short', code, length: code.length, minLength, trigger, source })
return
}
diagFlush({ trigger, source, length: code.length, durationMs })
// 记录完整条码:事后要能回答"这条到底扫到了什么"
diagFlush({ trigger, source, code, length: code.length, durationMs })
debug('flush-buffer', { code, length: code.length, durationMs, trigger, source })
if (receiver && typeof receiver.onScanCode === 'function') {
@ -159,14 +168,14 @@ function markKeyArrival(source) {
function onDomKeydown(event) {
markKeyArrival('dom')
if (!receiver || paused) {
diagDrop(receiver ? 'paused' : 'no-receiver', { source: 'dom' })
diagDrop(receiver ? 'paused' : 'no-receiver', { source: 'dom', buffer: bufferTail() })
return
}
const key = event?.key || ''
const isPrintable = key.length === 1
const isEnter = key === 'Enter'
if (!isPrintable && !isEnter) {
diagDrop('unmapped-dom-key', { key })
diagDrop('unmapped-dom-key', { key, buffer: bufferTail() })
return
}
debug('key-captured', { key, paused })
@ -294,7 +303,7 @@ function handlePlusKeyEvent(event, type) {
diagHeal('event-type-lock-idle-reset', { locked, gapMs: gap })
}
if (!receiver || paused) {
diagDrop(receiver ? 'paused' : 'no-receiver', { source: 'plus' })
diagDrop(receiver ? 'paused' : 'no-receiver', { source: 'plus', buffer: bufferTail() })
return
}
const keyCode = Number((event && event.keyCode) || 0)
@ -318,7 +327,7 @@ function handlePlusKeyEvent(event, type) {
plusShiftPrev = plusShiftDown
const isEnter = isPlusEnterKey(keyCode, text)
if (!text && !isEnter) {
diagDrop('unmapped-keycode', { keyCode, type })
diagDrop('unmapped-keycode', { keyCode, type, buffer: bufferTail() })
return
}
@ -327,7 +336,13 @@ function handlePlusKeyEvent(event, type) {
plusKeyEventType = type
}
if (plusKeyEventType !== type) {
diagDrop('event-type-locked', { keyCode, type, locked: plusKeyEventType })
// 这一类丢弃最致命(整串码会丢),必须带上已收到的内容
diagDrop('event-type-locked', {
keyCode,
type,
locked: plusKeyEventType,
dropped: bufferTail(),
})
return
}

View File

@ -172,7 +172,7 @@ import {
startScanSelfHeal,
stopScanSelfHeal,
} from '@/core/scan'
import { diagBegin, diagNote, diagPersistNow } from '@/core/scan-diag'
import { diagBegin, diagDrop, diagNote, diagPersistNow } from '@/core/scan-diag'
const qrBaseUrl = 'https://ye4s.wms.gztbyc.com/grcode/build?text='
const qrFallbackBaseUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=280x280&data='
@ -553,6 +553,8 @@ export default {
return
}
if (this.loginMode !== 'account' && this.loginMode !== 'scan') {
// 非扫码模式下收到的码被丢弃:记下内容与当前模式
diagDrop('mode-not-scan', { code, mode: String(this.loginMode || '') })
return
}
this.handleScanBadgeLogin(code, meta)
@ -1668,12 +1670,14 @@ export default {
this.logScanDebug('scan-login-abort', { reason: 'empty-code' })
return
}
diagNote('badge-login', { code })
const now = Date.now()
if (
this.scanBadgeSubmitting ||
(this.scanBadgeLastSubmittedCode === code && now - this.scanBadgeLastSubmittedAt < 1200)
) {
diagDrop('badge-duplicate', { code })
this.logScanDebug('scan-login-skipped', {
reason: this.scanBadgeSubmitting ? 'submitting' : 'duplicate-in-1200ms',
code,

View File

@ -341,6 +341,7 @@ import {
diagKey,
diagNote,
diagPersistNow,
diagSetContext,
diagSetGates,
} from '@/core/scan-diag'
@ -723,6 +724,7 @@ export default {
}
// 连续重复扫码限制:与上一次扫描内容一致时不执行任何操作
if (this.lastScannedCode === kw) {
diagDrop('duplicate-consecutive', { code: kw })
console.log('[packaging][scan] handlePackSearch skip: duplicate consecutive code =', kw)
this.keyword = ''
this.scheduleScanInputFocus(150)
@ -738,6 +740,7 @@ export default {
}
// 无在线成员:非工牌码(非用户码)拦截,不走查询用户,提示先登录
if (!this.workbenchMembers.length) {
diagDrop('no-member-intercept', { code: kw })
console.log('[packaging][scan] handlePackSearch -> 无成员且非工牌码,拦截')
this.keyword = ''
this.lastScannedCode = ''
@ -770,10 +773,12 @@ export default {
}
const token = this.getWorkbenchToken()
if (!token) {
diagDrop('no-workbench-token', { code })
uni.showToast({ title: '工作台登录已失效', icon: 'none' })
return
}
if (this.orderQuerying) {
diagDrop('query-busy', { code })
return
}
this.orderQuerying = true
@ -787,6 +792,7 @@ export default {
.catch(() => {
// 查询失败允许重扫同一码
this.lastScannedCode = ''
diagNote('query-failed', { code })
uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
})
.finally(() => {
@ -1019,6 +1025,15 @@ export default {
// 商品明细
this.detailList = this.mapOrderItems(items)
// 诊断上下文:“应该接收到的条码”= 本单商品条码;“当前任务”= 波次/运单
diagSetContext({
'期望任务': this.isGroupOrder
? `团单 ${this.currentWaveNo || ''}`
: `散单 ${this.currentWaybillCode || ''}`,
'期望条码': this.expectedBarcodeText(10),
'商品明细数': this.detailList.length,
})
// 免验商品(need_recheck=N)直接标记为已核实(标绿),无需扫码/长按
this.detailList.forEach((item) => {
if (item.needRecheck === 'N') {
@ -1064,12 +1079,14 @@ export default {
)
if (target) {
if (this.isItemScanned(target)) {
diagDrop('barcode-already-verified', { code: barcode })
this.keyword = ''
this.speak('数据一致')
uni.showToast({ title: '数据一致', icon: 'none', silentVoice: true })
return
}
// 按商品种类:扫 1 次即标记为已核实,无需扫满数量
diagNote('barcode-matched', { code: barcode, name: target.name || '' })
target.scannedQty = Number(target.qty) || 0
this.addScanRecord(barcode)
this.keyword = ''
@ -1078,10 +1095,20 @@ export default {
// 全部核实后自动开始打包
this.maybeAutoSubmitGroupPack()
} else {
// 收到码但业务不匹配:把"收到的码"与"期望的码"同时记下来
diagDrop('barcode-not-matched', { code: barcode, 期望条码: this.expectedBarcodeText(10) })
this.speak('无记录')
uni.showToast({ title: '条码与待核实商品不匹配', icon: 'none', silentVoice: true })
}
},
/** 期望条码文本(诊断日志用):本单商品条码,最多 limit 个 */
expectedBarcodeText(limit = 8) {
return this.detailList
.map((item) => item.barcode)
.filter((code) => !!code)
.slice(0, limit)
.join(',')
},
isItemScanned(item) {
const qty = Number(item?.qty) || 0
const scanned = Number(item?.scannedQty) || 0
@ -1349,6 +1376,8 @@ export default {
// 波次范围与打包时长闸门倒计时复位
this.currentWaveScope = null
this.stopPackCountdown()
// 诊断上下文同步复位(避免日志里残留上一单的期望条码)
diagSetContext({ '期望任务': '', '期望条码': '', '商品明细数': 0 })
},
speak(text) {
const str = this.normalizeSpeakText(text)
@ -2314,7 +2343,13 @@ export default {
this._plusKeyEventType = type
}
if (this._plusKeyEventType !== type) {
diagDrop('event-type-locked', { keyCode, type, locked: this._plusKeyEventType })
// 这一类丢弃最致命(整串码会丢),必须带上已收到的内容
diagDrop('event-type-locked', {
keyCode,
type,
locked: this._plusKeyEventType,
dropped: (this.plusKeyBuffer || '').slice(-40),
})
return
}
@ -2369,7 +2404,7 @@ export default {
if (!code) {
return
}
diagFlush({ trigger, source: 'plus', length: code.length, durationMs })
diagFlush({ trigger, source: 'plus', code, length: code.length, durationMs })
console.log('[packaging][scan] plus-buffer trigger =', trigger, 'code =', code)
this.submitScanCode(code, 'plus')
},
@ -2625,7 +2660,7 @@ export default {
return
}
this.lastSubmittedScan = { code: trimmed, at: now }
diagNote('submit-scan', { source, length: trimmed.length })
diagNote('submit-scan', { source, code: trimmed })
console.log('[packaging][scan] submitScanCode source =', source, 'code =', trimmed)
// 操作员弹窗打开时:弹窗已无输入框,关闭弹窗后扫码内容走主流程
if (this.operatorDialogVisible) {

View File

@ -443,7 +443,7 @@ import {
} from '@/api/camera'
import { registerScanReceiver, unregisterScanReceiver, setScanPaused, setScanMinLength, startScanSelfHeal, stopScanSelfHeal } from '@/core/scan'
import ScanDiagPanel from '@/components/scan-diag-panel.vue'
import { diagBegin, diagDrop, diagNote, diagPersistNow } from '@/core/scan-diag'
import { diagBegin, diagDrop, diagNote, diagPersistNow, diagSetContext } from '@/core/scan-diag'
// ==================== 扫码指令定义(与散单 Web 端 scan-commands.ts 一致) ====================
// 制式 Code 128,内容为简单单词,识别时 trim + 忽略大小写,与商品条码(纯数字)零冲突
@ -1033,9 +1033,21 @@ export default {
/** 扫码路由(全局捕获的完整码) */
handleScanCode(code, meta) {
const barcode = String(code || '').trim()
if (!barcode || this.modalBusy) return
console.log('[scan-returns] route', barcode, meta)
if (!barcode) {
return
}
if (this.modalBusy) {
// 弹窗期间收到的码被丢弃:记下内容,避免现场"扫了没反应"无法解释
diagDrop('modal-busy', { code: barcode, source: String((meta && meta.source) || '') })
return
}
const cmd = resolveScanCommand(barcode)
diagNote('scan-code', {
code: barcode,
cmd: cmd || 'code',
hasOrder: !!(this.createResult && this.createResult.id),
})
console.log('[scan-returns] route', barcode, meta)
this.routeScan(cmd, barcode)
},
@ -1126,6 +1138,12 @@ export default {
this.detailPage = 1
this.lastScannedBarcode = ''
this.orderDetailItems = []
// 诊断上下文:当前拆包单(现场对照"扫的码属于哪一单")
diagSetContext({
'当前运单': (this.createResult.record && this.createResult.record.waybill_code) || code,
'拆包单ID': data.id,
'拆包状态': (this.createResult.record && this.createResult.record.status) || '',
})
uni.showToast({ title: `拆包单创建成功,ID ${data.id}`, icon: 'none' })
this.pushOsdText()
this.loadDetailList()
@ -2113,6 +2131,8 @@ export default {
this.defaultProductStatus = 'normal'
this.orderDetailItems = []
this.lastScannedBarcode = ''
// 诊断上下文同步复位
diagSetContext({ '当前运单': '', '拆包单ID': 0, '拆包状态': 'idle' })
// 删除/取消/提交/清除后直接推「无任务」待命文字
this.pushOsdText(OSD_IDLE_TEXT)
// APP:隐藏输入框保持焦点(H5 全局监听无需焦点)