LogsWorker.js
2.82 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import config from '@/config.js'
import { serializeIfObject,deepClone } from '@/utils/utils.js'
export default class LogsWorker {
logFile = null
constructor() {
this.logFile = uni.$logger.local.logger
this.localLog = uni.$logger.local
this.isUploading = false
this.files = []
}
getLogFileList() {
return this.logFile.getLogFileList()
}
async upload(deviceId, data) {
if (this.isUploading) {
const msg = `日志上传中,请稍后再试!`
uni.$logger.local.info(msg)
this.ws.send(msg)
return
}
this.isUploading = true
try {
if (this.localLog && typeof this.localLog.flushAndClose === 'function') {
await this.localLog.flushAndClose()
}
let files = this.getLogFileList() || []
if (!files.length) {
await new Promise(r => setTimeout(r, 100))
files = this.getLogFileList() || []
}
this.files = JSON.stringify(files)
if (files.length) {
files.sort((a, b) => a.name.localeCompare(b.name))
this.process(files, deviceId)
} else {
const msg = `没有可上传的日志文件`
uni.$logger.local.info(msg)
this.ws.send({ code: 200, msg })
this.isUploading = false
this.files = []
}
} catch (e) {
const msg = `日志上传异常: ${e?.message || e}`
uni.$logger.local.error(msg)
this.ws.send({ code: 500, error: msg })
this.isUploading = false
this.files = []
}
}
async process(files, deviceId) {
try {
if (files.length > 0) {
const file = files.shift()
await this.post(file, deviceId)
setTimeout(() => this.process(files, deviceId), 500)
} else {
this.ws.send({ code: 200, msg: `日志上传完成 logs -> ${this.files}`})
this.isUploading = false
this.files = []
}
} catch (e) {
const msg = `日志处理异常: ${e?.message || e}`
uni.$logger.local.error(msg)
this.ws.send({ code: 500, error: msg })
this.isUploading = false
this.files = []
}
}
post({ name, path }, deviceId) {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: `${config.HTTP_SERVER}/${config.FILE_UPLOAD_URL}`,
filePath: path,
name: 'file',
header: {
'Content-Type': 'multipart/form-data'
},
formData: {
deviceId,
type: 'log'
},
success: res => {
uni.$logger.local.info(`文件上传成功! res->${serializeIfObject(res)} filePath->${path}`)
resolve()
},
fail: res => {
uni.$logger.local.error(`文件上传失败! res->${serializeIfObject(res)} filePath->${path} .`)
resolve()
}
})
})
}
work(deviceId, data, ws) {
this.ws = ws
this.upload(deviceId, data)
}
}