LogCat.js
6.11 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import { getTime } from './util'
import { serializeIfObject } from '../utils'
import TaskQueue from '../TaskQueue'
class LogCat {
main = plus.android.runtimeMainActivity()
File = plus.android.importClass('java.io.File')
Environment = plus.android.importClass('android.os.Environment')
BufferedWriter = plus.android.importClass('java.io.BufferedWriter')
FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
OutputStreamWriter = plus.android.importClass('java.io.OutputStreamWriter')
// BufferedReader = plus.android.importClass('java.io.BufferedReader')
// FileInputStream = plus.android.importClass('java.io.FileInputStream')
// InputStreamReader = plus.android.importClass('java.io.InputStreamReader')
LogPath = ''
// 日志写入队列,确保串行写入
taskQueue = new TaskQueue('LogCat')
// 记录上一次检查清理的日期,用于跨天触发清理
lastCleanDate = ''
constructor(folderName = '_zyzs_log') {
try {
let file = null
if (this.Environment.MEDIA_MOUNTED || !this.Environment.isExternalStorageRemovable()) {
file = this.main.getExternalFilesDir(null)
}
if (file) {
this.LogPath = file.getPath() + folderName
} else {
this.LogPath = this.main.getFilesDir().getPath() + folderName
}
// 初始化日志目录对象,避免每次写入都 new
this.logDirFile = new this.File(this.LogPath)
if (!this.logDirFile.exists()) {
this.logDirFile.mkdirs()
}
// 启动自动清理(清理7天前的日志)
this._cleanOldLogs(7)
this.lastCleanDate = getTime('YYYY-MM-DD')
} catch (e) {
console.error('LogCat init error:', e)
this.LogPath = ''
}
console.log('日志文件存放路径->', this.LogPath)
}
writeLog(tag, messages) {
// 将写入任务加入队列
this.taskQueue.enqueue(() => {
return new Promise((resolve) => {
// 延迟一小段时间执行,避免阻塞 UI 渲染
setTimeout(() => {
this._doWriteLog(tag, messages)
resolve()
}, 0)
})
})
}
// 真正的写入逻辑(私有方法)
_doWriteLog(tag, messages) {
// 如果路径初始化失败,直接放弃写入,避免报错
if (!this.LogPath) return
let msg = ''
try {
if (messages instanceof Error) {
msg = messages.stack || messages.message
} else if (messages === undefined) {
msg = 'undefined'
} else {
msg = serializeIfObject(messages)
}
} catch (e) {
msg = String(messages)
}
let date = getTime('YYYY-MM-DD')
// 检查跨天:如果当前日期与上次清理日期不同,触发一次清理
if (this.lastCleanDate && date !== this.lastCleanDate) {
this.lastCleanDate = date
this._cleanOldLogs(7)
}
let datetime = getTime()
//文件名
let fileName = this.LogPath + '/' + date + '.txt'
//写入的内容
let content = `${datetime} [${tag}] : ${msg}\n`
// 使用对应的 console 方法输出
const logFunc = console[tag] || console.log
logFunc(content.replace(/\n/g, ''))
// 移除重复的目录检查,仅在必要时(如目录被意外删除)才尝试重建
// let path = new this.File(this.LogPath)
// if (!path.exists()) {
// path.mkdirs()
// }
// 双重保险:虽然构造函数里创建了,但防止运行时目录被误删
if (this.logDirFile && !this.logDirFile.exists()) {
this.logDirFile.mkdirs()
}
let fos = null
let bw = null
try {
fos = new this.FileOutputStream(fileName, true)
bw = new this.BufferedWriter(new this.OutputStreamWriter(fos))
//bw.write(log);
bw.append(content)
} catch (e) {
console.log('e->', e)
} finally {
try {
if (bw != null) {
bw.close() //关闭缓冲流(会自动关闭底层fos)
} else if (fos != null) {
fos.close() //如果缓冲流创建失败,手动关闭文件流
}
} catch (closeEx) {
console.log('closeEx->', closeEx)
}
}
}
// 自动清理旧日志
_cleanOldLogs(daysToKeep) {
// 放入队列异步执行,不影响启动速度
this.taskQueue.enqueue(() => {
return new Promise((resolve) => {
setTimeout(() => {
try {
const list = this.getLogFileList()
const now = new Date().getTime()
const oneDay = 24 * 60 * 60 * 1000
list.forEach(file => {
// 文件名格式:YYYY-MM-DD.txt
const match = file.name.match(/^(\d{4}-\d{2}-\d{2})\.txt$/)
if (match) {
const fileDate = new Date(match[1]).getTime()
// 如果文件日期早于 (当前时间 - 保留天数),则删除
if (now - fileDate > daysToKeep * oneDay) {
this.removeLogFile(file.path)
}
}
})
} catch (e) {
console.error('清理旧日志失败:', e)
} finally {
resolve()
}
}, 1000) // 延迟1秒执行,避开App启动高峰
})
})
}
// 删除日志
removeLogFile(fileName) {
try {
let file = new this.File(fileName)
if (file.exists()) {
file.delete()
console.log('删除------' + fileName)
}
} catch (e) {
console.error('删除日志失败:', e)
}
}
// 获取所有日志文件列表
getLogFileList() {
try {
if (!this.LogPath) return []
let file = new this.File(this.LogPath)
if (!file.exists()) return []
let tempList = file.listFiles()
if (!tempList || tempList.length === 0) return []
// 注意:Java数组在NativeJS中可能没有map方法,建议使用循环
const list = []
for (let i = 0; i < tempList.length; i++) {
const f = tempList[i]
list.push({
name: f.getName(),
path: f.getPath()
})
}
return list
} catch (e) {
console.error('获取日志列表失败:', e)
return []
}
}
}
export default LogCat