index.js 2.29 KB
// 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()