RemoteLog.js
1.87 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
import sentryInit from '@/utils/sentryConfig/sentryInit'
import { LogLevel , RemoteExtraDataKey} from './constants'
import { getSystemInfo, hasPrivacyConsent } from '@/utils/deviceInfo'
class RemoteLog {
sentry = null
constructor(user) {
if (!hasPrivacyConsent()) return
this.sentry = sentryInit()
this.sentry.setUser(user)
}
isReady() {
return Boolean(this.sentry && hasPrivacyConsent())
}
debug(info) {
return this.send(LogLevel.DEBUG, info)
}
info(info) {
return this.send(LogLevel.INFO, info)
}
warn(info) {
return this.send(LogLevel.WARN, info)
}
error(info) {
return this.send(LogLevel.ERROR, info)
}
send(level, { extra = {}, msg, tag = { key: '', value: '' } } = {}) {
if (!this.isReady()) return false
this.sentry.withScope(scope => {
if (tag && tag.key) {
scope.setTag(tag.key, tag.value)
}
// 记录更多上下文信息
scope.setExtra(RemoteExtraDataKey, extra)
scope.setLevel(level)
// 添加设备信息到 extra
const systemInfo = getSystemInfo()
if (systemInfo) {
scope.setExtra('device_brand', systemInfo.brand)
scope.setExtra('device_model', systemInfo.model)
scope.setExtra('os_version', systemInfo.system)
scope.setExtra('app_version', systemInfo.appVersion)
}
// 区分 Error 对象和普通消息
if (msg instanceof Error) {
this.sentry.captureException(msg)
} else {
this.sentry.captureMessage(String(msg))
}
})
return true
}
async close() {
const sentry = this.sentry
this.sentry = null
if (!sentry || typeof sentry.close !== 'function') return false
try {
await sentry.close(2000)
return true
} catch (error) {
console.warn('[RemoteLog] Sentry关闭失败', error)
return false
}
}
}
export default RemoteLog