LocalLog.js
2.96 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
98
99
100
101
102
103
104
105
106
/*
* @Author: cen
* @Date: 2026-04-01 15:45:44
* @Description:
* @FilePath: /gl_tape/utils/logger/LocalLog.js
* @LastEditTime: 2026-04-08 15:23:26
* @LastEditors: cenchengwei@foreverht.com
* 可以输入预定的版权声明、个性签名、空行等
*/
import LogCat from './LogCat'
import FloatLogBus from './FloatLogBus.js'
import { LogLevel } from './constants'
import { getTime, withinSpliter, daysBetween } from './util'
function mirrorToConsole(level, msg) {
const text = msg == null ? '' : typeof msg === 'string' ? msg : String(msg)
if (!text) return
const oc = FloatLogBus.getOriginalConsole?.()
if (level === LogLevel.ERROR) {
;(oc?.error || console.error)(text)
} else if (level === LogLevel.WARN) {
;(oc?.warn || console.warn)(text)
} else if (level === LogLevel.DEBUG) {
;(oc?.debug || console.debug)(text)
} else {
;(oc?.log || console.log)(text)
}
}
class LocalLog {
logger = null
logListener = null
constructor() {
// #ifdef APP-PLUS
this.logger = new LogCat()
this.removeOverDays(90)
// #endif
}
setLogListener (listener) {
this.logListener = listener
}
_write (level, msg) {
// #ifdef APP-PLUS
this.logger.writeLog(level, msg)
mirrorToConsole(level, msg)
if (this.logListener) {
try {
this.logListener(level, msg)
} catch (e) {
console.error('LocalLog listener error', e)
}
}
// #endif
}
debug (msg) {
this._write(LogLevel.DEBUG, msg)
}
info (msg) {
this._write(LogLevel.INFO, msg)
}
warn (msg) {
this._write(LogLevel.WARN, msg)
}
error (msg) {
this._write(LogLevel.ERROR, msg)
}
getFiles (beginDate, endDate) {
const logFiles = this.logger.getLogFileList()
if ((!beginDate && !endDate) || !logFiles.length) return logFiles
beginDate = +withinSpliter(beginDate)
endDate = +withinSpliter(endDate)
// prettier-ignore
const fileList = logFiles.reduce((list, { name, path }) => {
const fileDate = +withinSpliter(name.split('.').shift())
if (fileDate >= beginDate && fileDate <= endDate) {
list.push(path)
}
return list
}, []);
// console.log('fileList', fileList)
// this.logger.zip(fileList)
return fileList
}
removeOverDays (day = 7) {
this.logger._cleanOldLogs(day)
// const logFiles = this.logger.getLogFileList()
// if (!logFiles.length) return
// const today = getTime('YYYY-MM-DD')
// logFiles.forEach(({ name, path }) => {
// const fileDate = name.split('.').shift()
// if (daysBetween(fileDate, today) > day) {
// this.logger.removeLogFile(path)
// }
// })
}
// 等待写入队列清空并强制关闭当前文件流,确保日志完整落盘
async flushAndClose () {
// #ifdef APP-PLUS
if (this.logger && typeof this.logger.flushAndClose === 'function') {
return this.logger.flushAndClose()
}
// #endif
return Promise.resolve()
}
}
export default LocalLog