LiveLogWorker.js
1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { serializeIfObject } from '@/utils/utils.js'
export default class LiveLogWorker {
constructor() {}
work(deviceId, data, ws) {
const { action } = data // 'start' | 'stop'
if (action === 'start') {
uni.$logger.local.info('[LiveLogWorker] 开启实时日志流')
// 设置监听器
uni.$logger.setLogListener((level, info) => {
// 防止死循环:这里发送 WS 消息,如果 WS 发送失败导致 logger.error,会再次触发监听器
// 简单处理:只发送非 WS 相关的日志,或者信任 WS 库不会在 send 时狂打日志
// 这里直接发送
try {
// 构造日志消息对象
const logMsg = {
type: 'liveLog',
level,
info: typeof info === 'object' ? serializeIfObject(info) : info,
timestamp: Date.now()
}
// 直接调用底层的 ws 发送,跳过 logging 避免循环
// 注意:ws 是 Ws.js 中的实例,ws.ws 是 socket.io 实例
if (ws && ws.ws && ws.ws.connected) {
ws.ws.emit('message', logMsg)
}
} catch (e) {
// 忽略发送错误,避免死循环
console.error('Live log send failed', e)
}
})
ws.send({ code: 200, msg: '实时日志已开启' })
} else if (action === 'stop') {
uni.$logger.setLogListener(null)
uni.$logger.local.info('[LiveLogWorker] 关闭实时日志流')
ws.send({ code: 200, msg: '实时日志已关闭' })
} else {
ws.send({ error: '未知动作: ' + action })
}
}
}