RemoteLog.js 1.87 KB
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