index.js
2.29 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
// import { index } from './env'
import LocalLog from './LocalLog'
import { LogLevel } from './constants'
import { storageApi } from '../cache'
import { getIp } from './util'
import store from '@/store'
class Logger {
remote = null
local = null
fields = []
constructor(fields = []) {
this.fields = fields
this.init()
}
init() {
// 本地日志立即初始化,确保记录每一个用户操作
this.local = new LocalLog()
// remote(Sentry)动态导入延迟初始化,等用户同意隐私政策后由 initRemote() 调用
}
// 延迟初始化远程日志(Sentry),在用户同意隐私政策后调用
// overrides: 可选的用户信息覆盖,用于初始化时 userInfo 尚未完整的情况
async initRemote(overrides = {}) {
if (!store.getters.hasPrivacyConsent) {
this.local.warn('Sentry初始化已跳过:用户未同意隐私协议')
return false
}
if (this.remote?.isReady?.()) return true
const { default: RemoteLog } = await import('./RemoteLog')
const user = { ...this.getUserInfo(), ...overrides }
this.remote = new RemoteLog(user)
if (!this.remote.isReady()) {
this.remote = null
return false
}
return true
}
async disableRemote() {
const remote = this.remote
this.remote = null
if (!remote) return false
return remote.close()
}
debug(info) {
this.write(LogLevel.DEBUG, info)
}
info(info) {
this.write(LogLevel.INFO, info)
}
warn(info) {
this.write(LogLevel.WARN, info)
}
error(info) {
this.write(LogLevel.ERROR, info)
}
write(level, info) {
if (this.remote && store.getters.hasPrivacyConsent) {
// RemoteLog.send() 期望 { msg, extra, tag } 结构,字符串需包装
const remoteInfo = typeof info === 'string' ? { msg: info } : info
this.remote[level](remoteInfo)
} else if (this.remote) {
this.disableRemote()
}
this.local[level](info)
}
getUserInfo() {
const userInfo = storageApi.getUserInfo() || {}
// const ip = await getIp()
const user = this.fields.reduce((pre, cur) => {
pre[cur] = userInfo[cur] || ''
return pre
}, {})
user.name = userInfo.name || ''
user.merchantName = userInfo.merchantName || ''
// user.ip = ip
return user
}
}
export default new Logger()