FloatLogBus.js 4.78 KB
import { LogLevel } from './constants'
import { serializeIfObject } from '../utils'

import FloatLogConfig from './FloatLogConfig.js'

const MAX_LINES = 400
const PIN_TAG = '[StoragePathMerge]'
const MAX_PINNED_LINES = 60

function trimLines() {
  if (lines.length <= MAX_LINES) return
  const pinned = lines.filter(l => l.text.includes(PIN_TAG))
  const normal = lines.filter(l => !l.text.includes(PIN_TAG))
  const pinnedKeep = pinned.slice(-MAX_PINNED_LINES)
  const normalBudget = Math.max(0, MAX_LINES - pinnedKeep.length)
  const normalKeep = normal.slice(-normalBudget)
  lines = [...normalKeep, ...pinnedKeep]
  lines.sort((a, b) => {
    const ta = parseInt(String(a.id).split('_')[0], 10) || 0
    const tb = parseInt(String(b.id).split('_')[0], 10) || 0
    return ta - tb
  })
}

let lines = []
/** 路径合并等启动期日志,单独保留,避免被后续刷屏挤掉 */
let mergeLines = []
let listeners = new Set()
let installed = false
let originalConsole = null

function pad(n) {
  return n < 10 ? '0' + n : String(n)
}

function nowTime() {
  const d = new Date()
  const ms = String(d.getMilliseconds())
  const ms3 = ms.length >= 3 ? ms : ('00' + ms).slice(-3)
  return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${ms3}`
}

function normalizeLevel(level) {
  const l = String(level || 'info').toLowerCase()
  if (l === LogLevel.DEBUG || l === 'debug') return 'debug'
  if (l === LogLevel.WARN || l === 'warn') return 'warn'
  if (l === LogLevel.ERROR || l === 'error') return 'error'
  return 'info'
}

function formatPayload(payload) {
  if (payload == null) return ''
  if (typeof payload === 'string') return payload
  if (payload instanceof Error) {
    return payload.stack || payload.message || String(payload)
  }
  if (typeof payload === 'object') {
    if (payload.msg != null) {
      const extra = payload.extra != null ? ` ${serializeIfObject(payload.extra)}` : ''
      return String(payload.msg) + extra
    }
    try {
      return serializeIfObject(payload)
    } catch (e) {
      return String(payload)
    }
  }
  return String(payload)
}

function joinArgs(args) {
  return args.map(a => formatPayload(a)).filter(Boolean).join(' ')
}

function pushLine(level, text) {
  const msg = formatPayload(text)
  if (!msg) return
  const line = {
    id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
    time: nowTime(),
    level: normalizeLevel(level),
    text: msg
  }
  lines.push(line)
  if (msg.includes(PIN_TAG)) {
    mergeLines.push(line)
    if (mergeLines.length > MAX_PINNED_LINES) {
      mergeLines = mergeLines.slice(mergeLines.length - MAX_PINNED_LINES)
    }
  }
  trimLines()
  listeners.forEach(fn => {
    try {
      fn(line)
    } catch (e) {
      /* ignore */
    }
  })
}

function patchConsole() {
  if (originalConsole) return
  originalConsole = {
    log: console.log.bind(console),
    info: console.info.bind(console),
    warn: console.warn.bind(console),
    error: console.error.bind(console),
    debug: console.debug.bind(console)
  }
  console.log = (...args) => {
    originalConsole.log(...args)
    pushLine('info', joinArgs(args))
  }
  console.info = (...args) => {
    originalConsole.info(...args)
    pushLine('info', joinArgs(args))
  }
  console.warn = (...args) => {
    originalConsole.warn(...args)
    pushLine('warn', joinArgs(args))
  }
  console.error = (...args) => {
    originalConsole.error(...args)
    pushLine('error', joinArgs(args))
  }
  console.debug = (...args) => {
    originalConsole.debug(...args)
    pushLine('debug', joinArgs(args))
  }
}

const FloatLogBus = {
  isInstalled() {
    return installed
  },

  getOriginalConsole() {
    return originalConsole
  },

  install() {
    if (installed) return
    installed = true
    patchConsole()
    if (uni.$logger && typeof uni.$logger.setLogListener === 'function') {
      uni.$logger.setLogListener((level, info) => {
        pushLine(level, info)
      })
    }
    pushLine('info', '[FloatLogBus] 日志悬浮窗已就绪')
  },

  isFloatLogEnabled() {
    return FloatLogConfig.isLogBallVisible()
  },

  push(level, text) {
    pushLine(level, text)
  },

  subscribe(fn) {
    listeners.add(fn)
    return () => listeners.delete(fn)
  },

  getLineCount() {
    return lines.length
  },

  getLines() {
    return lines.slice()
  },

  /** 仅路径合并相关日志(冷启动后仍可在悬浮窗看到) */
  getMergeLines() {
    return mergeLines.slice()
  },

  /** 取尾部日志,避免面板一次性拷贝/渲染过多 */
  getRecentLines(limit = 200) {
    if (!limit || lines.length <= limit) return lines.slice()
    return lines.slice(lines.length - limit)
  },

  clearLines() {
    lines = []
    mergeLines = []
    listeners.forEach(fn => {
      try {
        fn(null)
      } catch (e) {
        /* ignore */
      }
    })
  }
}

export default FloatLogBus