Commit a39a640f by yixinjj

完善日志管理功能

1 parent de7c6ccf
...@@ -26,7 +26,9 @@ export default { ...@@ -26,7 +26,9 @@ export default {
this.wv = await this.initWebview() this.wv = await this.initWebview()
await this.enQueue() await this.enQueue()
this.polling() this.polling()
// uni.$logger.error({ extra : { key: 'data', value: {'abc':123,'sss':456,'GDF':888} }, msg:'test', tag : { key: 'test', value: 'test' } }) // uni.$logger.local.error({ extra : { key: 'data', value: {'abc':123,'sss':456,'GDF':888} }, msg:'test', tag : { key: 'tag', value: 'tagtest' } })
// uni.$logger.local.getFiles('20240905','2024-09/05')
// uni.$logger.local.removeOverDays(1)
}, },
/** /**
* 处理消息函数 * 处理消息函数
...@@ -49,7 +51,7 @@ export default { ...@@ -49,7 +51,7 @@ export default {
} catch (e) { } catch (e) {
this.reportError(recordId, fileName, e) this.reportError(recordId, fileName, e)
} finally { } finally {
console.log('本次任务完成,开启下一次上传任务!') uni.$logger.local.info('本次任务完成,开启下一次上传任务!')
this.polling() this.polling()
} }
}, },
...@@ -58,8 +60,9 @@ export default { ...@@ -58,8 +60,9 @@ export default {
*/ */
reportError(recordId, filePath, res) { reportError(recordId, filePath, res) {
const { customerName, phoneNumber, carModel, salesName } = uni.$recordManager.getRecordById(recordId) || {} const { customerName, phoneNumber, carModel, salesName } = uni.$recordManager.getRecordById(recordId) || {}
const { name } = uni.$storage.get('userInfo') || {} // const { name } = uni.$storage.get('userInfo') || {}
this.$sendSentry(`上传失败:文件-${filePath} 手机号-${phoneNumber} 姓名-${customerName} 销售-${salesName} 车型-${carModel} 员工-${name}失败原因-${JSON.stringify(res)}`) uni.$logger.error({ msg: '上传文件失败!!', extra: { '手机号: ': phoneNumber, '姓名: ': customerName, '销售: ': salesName, '车型: ': carModel, '原因: ': JSON.stringify(res), '文件路径: ': filePath } })
// this.$sendSentry(`上传失败:文件-${filePath} 手机号-${phoneNumber} 姓名-${customerName} 销售-${salesName} 车型-${carModel} 员工-${name}失败原因-${JSON.stringify(res)}`)
}, },
/** /**
* 初始化 WebView 的异步函数 * 初始化 WebView 的异步函数
...@@ -100,9 +103,11 @@ export default { ...@@ -100,9 +103,11 @@ export default {
*/ */
async enQueue() { async enQueue() {
// uni.$logger.remote.error({ extra : { key: 'data', value: {test:'test'} }, msg:'test', tag : { key: 'test', value: 'test' } }) // uni.$logger.remote.error({ extra : { key: 'data', value: {test:'test'} }, msg:'test', tag : { key: 'test', value: 'test' } })
// uni.$logger.local.info('开始创建上传文件快照.')
const _snapshot = await this.getRecordsSnapshotFlatten() const _snapshot = await this.getRecordsSnapshotFlatten()
this.snapshot = new Queue(_snapshot) this.snapshot = new Queue(_snapshot)
console.log('创建任务快照.下一轮快照文件个数:', this.snapshot.size) uni.$logger.local.info('创建快照成功! 文件个数:' + this.snapshot.size)
// console.log('创建任务快照.下一轮快照文件个数:', this.snapshot.size)
}, },
/** /**
* 获取记录快照并展平数据 * 获取记录快照并展平数据
...@@ -129,7 +134,8 @@ export default { ...@@ -129,7 +134,8 @@ export default {
*/ */
async uploadRecord(record) { async uploadRecord(record) {
const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await getOssToken() const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await getOssToken()
console.log('获取Token成功!!', `lsaccessKeySecret: ${lsaccessKeySecret}, lsaccessKeyId: ${lsaccessKeyId}`) uni.$logger.local.info(`获取Token成功,开始文件上传(webview)!!', lsaccessKeySecret: ${lsaccessKeySecret}, lsaccessKeyId: ${lsaccessKeyId}`)
// console.log('获取Token成功!!', `lsaccessKeySecret: ${lsaccessKeySecret}, lsaccessKeyId: ${lsaccessKeyId}`)
this.wv.evalJS(`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}','${record.recordId}')`) this.wv.evalJS(`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}','${record.recordId}')`)
}, },
/** /**
...@@ -150,8 +156,9 @@ export default { ...@@ -150,8 +156,9 @@ export default {
async uploadSuccess(recordId, filePathOnServer, filePathOnClient, fileName) { async uploadSuccess(recordId, filePathOnServer, filePathOnClient, fileName) {
const unlock = await uni.$recordManager.lock() const unlock = await uni.$recordManager.lock()
try { try {
uni.$logger.local.info(`文件上传成功!!', filePathOnServer-> ${filePathOnServer}, filePathOnClient-> ${filePathOnClient} , fileName-> ${fileName}`)
const record = uni.$recordManager.getRecordById(recordId) const record = uni.$recordManager.getRecordById(recordId)
if (!record) return if (!record) return uni.$logger.local.info(`未找到接待记录!!`)
this._changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName) this._changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName)
await this._saveOrUpdate(record, filePathOnClient) await this._saveOrUpdate(record, filePathOnClient)
} catch (err) { } catch (err) {
...@@ -173,12 +180,15 @@ export default { ...@@ -173,12 +180,15 @@ export default {
* @throws {Error} 如果 record 参数无效或 recordFileList 属性不存在,将抛出错误 * @throws {Error} 如果 record 参数无效或 recordFileList 属性不存在,将抛出错误
*/ */
_changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName) { _changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName) {
uni.$logger.local.info(`开始将接待记录的文件路径改成服务器路径!! record.recordUrlList-> ${JSON.stringify(record.recordUrlList)}`)
record.recordUrlList?.forEach(fileInfo => { record.recordUrlList?.forEach(fileInfo => {
if (fileInfo.file === filePathOnClient || fileInfo.file.endsWith(fileName)) { if (fileInfo.file === filePathOnClient || fileInfo.file.endsWith(fileName)) {
fileInfo.file = filePathOnServer fileInfo.file = filePathOnServer
delete fileInfo.status delete fileInfo.status
uni.$logger.local.info(`修改文件路径完成并删除文件status属性!! fileInfo.file-> ${fileInfo.file} fileInfo.status-> ${fileInfo.status}`)
} }
}) })
uni.$logger.local.info(`替换完成!! record.recordUrlList-> ${JSON.stringify(record.recordUrlList)}`)
}, },
/** /**
* 从客户端移除文件 * 从客户端移除文件
...@@ -189,11 +199,13 @@ export default { ...@@ -189,11 +199,13 @@ export default {
* @throws {Error} 如果 filePathOnClient 参数无效或文件删除过程中发生错误,将抛出错误 * @throws {Error} 如果 filePathOnClient 参数无效或文件删除过程中发生错误,将抛出错误
*/ */
_removeFileOnClient(filePathOnClient) { _removeFileOnClient(filePathOnClient) {
uni.$logger.local.info(`开始删除客户端的文件!! 路径-> ${filePathOnClient}`)
//删除客户端的文件 //删除客户端的文件
uni.removeSavedFile({ uni.removeSavedFile({
filePath: filePathOnClient, filePath: filePathOnClient,
complete: function (res) { complete: function (res) {
console.log(res) // console.log(res)
uni.$logger.local.info(`删除成功!!`)
} }
}) })
}, },
...@@ -208,15 +220,20 @@ export default { ...@@ -208,15 +220,20 @@ export default {
* @throws {Error} 如果在保存或更新记录时发生错误,将抛出错误 * @throws {Error} 如果在保存或更新记录时发生错误,将抛出错误
*/ */
async _saveOrUpdate(record, filePathOnClient) { async _saveOrUpdate(record, filePathOnClient) {
uni.$logger.local.info(`开始保存或更新接待记录!! record-> ${JSON.stringify(record)}`)
if (record.recordUrlList?.every(i => i.status == undefined)) { if (record.recordUrlList?.every(i => i.status == undefined)) {
const pathArr = record.recordUrlList.map(i => i.file) const pathArr = record.recordUrlList.map(i => i.file)
const params = { ...record, recordUrlList: pathArr } const params = { ...record, recordUrlList: pathArr }
uni.$logger.local.info(`记录中的文件已全部上传,开始向服务器保存接待记录!!`)
const res = await uni.$api.commonApi.saveRecCustomer(params) const res = await uni.$api.commonApi.saveRecCustomer(params)
uni.$logger.local.info(`服务器返回结果: ${res}`)
if (res) { if (res) {
uni.$logger.local.info(`保存接待记录成功,开始删除本地接待记录!!`)
uni.$recordManager.removeRecord(record.id) uni.$recordManager.removeRecord(record.id)
this._removeFileOnClient(filePathOnClient) this._removeFileOnClient(filePathOnClient)
} }
} else { } else {
uni.$logger.local.info(`记录中有未上传文件,开始更新记录!!`)
uni.$recordManager.updateRecord(record) uni.$recordManager.updateRecord(record)
this._removeFileOnClient(filePathOnClient) this._removeFileOnClient(filePathOnClient)
} }
...@@ -268,11 +285,11 @@ export default { ...@@ -268,11 +285,11 @@ export default {
* @throws {Error} 如果在上传过程中发生错误,将抛出错误,延迟 interval 后继续 polling * @throws {Error} 如果在上传过程中发生错误,将抛出错误,延迟 interval 后继续 polling
*/ */
polling() { polling() {
console.log(this.snapshot.size, '当前待上传文件快照数量') // uni.$logger.local.info(`当前待上传文件快照数量-> ${this.snapshot.size}`)
// console.log(this.snapshot.size, '当前待上传文件快照数量')
if (this.snapshot === null) return if (this.snapshot === null) return
// prettier-ignore // prettier-ignore
uni.$isNetWork().then(this.upload).catch(e =>{ uni.$isNetWork().then(this.upload).catch(e =>{
console.log('网络错误',e);
this.reportError('', '异常', e) this.reportError('', '异常', e)
this.pollingLater(interval) this.pollingLater(interval)
}) })
...@@ -304,6 +321,7 @@ export default { ...@@ -304,6 +321,7 @@ export default {
this.snapshot = null this.snapshot = null
} }
if (timer) clearTimeout(timer) if (timer) clearTimeout(timer)
uni.$logger.local.info(`停止文件上传轮询并清除队列`)
}, },
/** /**
* 在指定的时间间隔后启动轮询 * 在指定的时间间隔后启动轮询
......
import LogCat from './LogCat' import LogCat from './LogCat'
import { LogLevel } from './constants' import { LogLevel } from './constants'
import { getTime, withinSpliter, daysBetween } from './util'
class LocalLog { class LocalLog {
logger = null logger = null
constructor() { constructor() {
this.logger = LogCat this.logger = new LogCat()
this.logger.init()
} }
debug(msg) { debug(msg) {
this.logger.writeLog(LogLevel.DEBUG, msg) this.logger.writeLog(LogLevel.DEBUG, msg)
...@@ -18,5 +18,33 @@ class LocalLog { ...@@ -18,5 +18,33 @@ class LocalLog {
error(msg) { error(msg) {
this.logger.writeLog(LogLevel.ERROR, msg) this.logger.writeLog(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) {
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)
}
})
}
} }
export default LocalLog export default LocalLog
import { getTime } from './util' import { getTime } from './util'
const LogCat = { class LogCat {
main: plus.android.runtimeMainActivity(), main = plus.android.runtimeMainActivity()
Environment: plus.android.importClass('android.os.Environment'), File = plus.android.importClass('java.io.File')
BufferedWriter: plus.android.importClass('java.io.BufferedWriter'), Environment = plus.android.importClass('android.os.Environment')
BufferedReader: plus.android.importClass('java.io.BufferedReader'), BufferedWriter = plus.android.importClass('java.io.BufferedWriter')
File: plus.android.importClass('java.io.File'), FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
FileOutputStream: plus.android.importClass('java.io.FileOutputStream'), OutputStreamWriter = plus.android.importClass('java.io.OutputStreamWriter')
FileInputStream: plus.android.importClass('java.io.FileInputStream'), // BufferedReader = plus.android.importClass('java.io.BufferedReader')
OutputStreamWriter: plus.android.importClass('java.io.OutputStreamWriter'), // FileInputStream = plus.android.importClass('java.io.FileInputStream')
InputStreamReader: plus.android.importClass('java.io.InputStreamReader'), // InputStreamReader = plus.android.importClass('java.io.InputStreamReader')
LogPath: '', LogPath = ''
init: function (folderName = '_zyzs_log') { constructor(folderName = '_zyzs_log') {
if (this.Environment.MEDIA_MOUNTED || !this.Environment.isExternalStorageRemovable()) { if (this.Environment.MEDIA_MOUNTED || !this.Environment.isExternalStorageRemovable()) {
this.LogPath = this.main.getExternalFilesDir(null).getPath() + folderName this.LogPath = this.main.getExternalFilesDir(null).getPath() + folderName
} else { } else {
this.LogPath = this.main.getFilesDir().getPath() + folderName this.LogPath = this.main.getFilesDir().getPath() + folderName
} }
console.log('日志文件存放路径->', this.LogPath) console.log('日志文件存放路径->', this.LogPath)
}, }
writeLog: function (tag, msg) { writeLog(tag, msg) {
let date = getTime('YYYY-MM-DD') let date = getTime('YYYY-MM-DD')
let datetime = getTime() let datetime = getTime()
msg = typeof msg !== 'string' ? JSON.stringify(msg) : msg msg = typeof msg !== 'string' ? JSON.stringify(msg) : msg
//文件名 //文件名
let fileName = this.LogPath + date + '.txt' let fileName = this.LogPath + '/' + date + '.txt'
//写入的内容 //写入的内容
let content = `${datetime} ${tag}:${msg}\n` let content = `${datetime} [${tag}]:${msg}\n`
let path = new this.File(this.LogPath)
let file = new this.File(this.LogPath) if (!path.exists()) {
if (!file.exists()) { path.mkdirs() //创建父路径
file.mkdirs() //创建父路径
} }
let fos = null let fos = null
let bw = null let bw = null
...@@ -52,67 +49,27 @@ const LogCat = { ...@@ -52,67 +49,27 @@ const LogCat = {
console.log('closeEx->', closeEx) console.log('closeEx->', closeEx)
} }
} }
}, }
// 删除日志 // 删除日志
removeLogFile: function (fileName) { removeLogFile(fileName) {
let file = new this.File(fileName) let file = new this.File(fileName)
let fos = new this.FileOutputStream(fileName, true) let fos = new this.FileOutputStream(fileName, true)
fos.close() fos.close()
file.delete() file.delete()
console.log('删除------' + fileName) console.log('删除------' + fileName)
}, }
// 获取所有日志文件列表 // 获取所有日志文件列表
getLogFileList: function () { getLogFileList() {
let list = []
let file = new this.File(this.LogPath) let file = new this.File(this.LogPath)
let tempList = file.listFiles() let tempList = file.listFiles()
for (let i = 0; i < tempList.length; i++) { if (!tempList || tempList.length === 0) return []
let fileName = tempList[i].getName() const list = tempList.map(file => {
let filePath = tempList[i].getPath() return {
let obj = { name: file.getName(),
name: fileName, path: file.getPath()
filePath: filePath
}
list.push(obj)
}
return list
},
// 读取日志具体内容
readLog: function (path) {
// 编码格式
const charset = 'utf-8'
let file = new this.File(path)
let inputStreamReader = null
let bufferedReader = null
let list = []
try {
//不存在
if (!file.exists()) {
return list
}
inputStreamReader = new this.InputStreamReader(new this.FileInputStream(file), charset)
bufferedReader = new this.BufferedReader(inputStreamReader)
let line = ''
while (null != (line = bufferedReader.readLine())) {
if (line) {
list.push(line)
}
} }
bufferedReader.close() })
inputStreamReader.close()
} catch (e) {
console.error(e)
if (bufferedReader) {
bufferedReader.close()
}
if (inputStreamReader) {
inputStreamReader.close()
}
return list
}
return list return list
} }
} }
export default LogCat export default LogCat
import sentryInit from '@/utils/sentryConfig/sentryInit' import sentryInit from '@/utils/sentryConfig/sentryInit'
import { LogLevel } from './constants' import { LogLevel , RemoteExtraDataKey} from './constants'
class RemoteLog { class RemoteLog {
sentry = null sentry = null
constructor(user) { constructor(user) {
...@@ -18,12 +18,12 @@ class RemoteLog { ...@@ -18,12 +18,12 @@ class RemoteLog {
error(info) { error(info) {
this.send(LogLevel.ERROR, info) this.send(LogLevel.ERROR, info)
} }
send(level, { extra = { key: 'data', value: {} }, msg, tag = { key: '', value: '' } }) { send(level, { extra = {}, msg, tag = { key: '', value: '' } }) {
this.sentry.withScope(scope => { this.sentry.withScope(scope => {
scope.setTag(tag.key, tag.value) scope.setTags(tag.key, tag.value)
scope.setExtra(extra.key, extra.value) scope.setExtra(RemoteExtraDataKey, extra)
scope.setLevel(level) scope.setLevel(level)
this.sentry.captureException(msg) this.sentry.captureException(new Error(msg))
}) })
} }
} }
......
const LogLevel = { export const LogLevel = {
DEBUG: 'debug', DEBUG: 'debug',
INFO: 'info', INFO: 'info',
WARN: 'warn', WARN: 'warn',
ERROR: 'error' ERROR: 'error'
} }
export { LogLevel } export const RemoteExtraDataKey = 'data'
...@@ -18,29 +18,32 @@ class Logger { ...@@ -18,29 +18,32 @@ class Logger {
this.local = new LocalLog() this.local = new LocalLog()
} }
debug(info) { debug(info) {
this.white(LogLevel.DEBUG, info) this.write(LogLevel.DEBUG, info)
} }
info(info) { info(info) {
this.white(LogLevel.INFO, info) this.write(LogLevel.INFO, info)
} }
warn(info) { warn(info) {
this.white(LogLevel.WARN, info) this.write(LogLevel.WARN, info)
} }
error(info) { error(info) {
this.white(LogLevel.ERROR, info) this.write(LogLevel.ERROR, info)
} }
white(level, info) { write(level, info) {
this.remote[level](info) this.remote[level](info)
this.local[level](JSON.stringify(info)) this.local[level](JSON.stringify(info))
} }
async getUserInfo() { async getUserInfo() {
const userInfo = storageApi.getUserInfo() const userInfo = storageApi.getUserInfo()
console.log('userInfo', userInfo);
const ip = await getIp() const ip = await getIp()
const user = this.fields.reduce((pre, cur) => { const user = this.fields.reduce((pre, cur) => {
pre[cur] = userInfo[cur] pre[cur] = userInfo[cur]
return pre return pre
}, {}) }, {})
user.name = userInfo.name user.name = userInfo.name
user.merchantName = userInfo.merchantName
user.ip = ip user.ip = ip
return user return user
} }
......
...@@ -81,4 +81,13 @@ const getIp = () => { ...@@ -81,4 +81,13 @@ const getIp = () => {
}) })
} }
export { getTime, getIp } const withinSpliter = (dateStr) => {
return dateStr.replace(/[-\/]/g, '')
}
const daysBetween = (startDate, endDate) => {
const start = new Date(startDate)
const end = new Date(endDate)
const days = (end - start) / (1000 * 60 * 60 * 24)
return Math.floor(days)
}
export { getTime, getIp, withinSpliter, daysBetween }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!