RemoteLog.js 1.36 KB
import sentryInit from '@/utils/sentryConfig/sentryInit'
import { LogLevel , RemoteExtraDataKey} from './constants'
class RemoteLog {
  sentry = null
  constructor(user) {
    this.sentry = sentryInit()
    this.sentry.setUser(user)
  }
  debug(info) {
    this.send(LogLevel.DEBUG, info)
  }
  info(info) {
    this.send(LogLevel.INFO, info)
  }
  warn(info) {
    this.send(LogLevel.WARN, info)
  }
  error(info) {
    this.send(LogLevel.ERROR, info)
  }
  send(level, { extra = {}, msg, tag = { key: '', value: '' } }) {
    this.sentry.withScope(scope => {
      if (tag && tag.key) {
        scope.setTag(tag.key, tag.value)
      }
      
      // 记录更多上下文信息
      scope.setExtra(RemoteExtraDataKey, extra)
      scope.setLevel(level)
      
      // 添加设备信息到 extra
      try {
        const systemInfo = uni.getSystemInfoSync()
        scope.setExtra('device_brand', systemInfo.brand)
        scope.setExtra('device_model', systemInfo.model)
        scope.setExtra('os_version', systemInfo.system)
        scope.setExtra('app_version', systemInfo.appVersion)
      } catch (e) {
        // 忽略获取设备信息失败
      }

      // 区分 Error 对象和普通消息
      if (msg instanceof Error) {
        this.sentry.captureException(msg)
      } else {
        this.sentry.captureMessage(String(msg))
      }
    })
  }
}
export default RemoteLog