JS 日志过大是前端常见的问题,可以从产生、传输、存储、展示四个环节来处理。下面按实用程度给你一个系统性的解决方案。
// 生产环境只保留 error / warn
const LOG_LEVEL = process.env.NODE_ENV === 'production' ? 'error' : 'debug'
function log(level, ...args) {
if (level < LOG_LEVEL) return
console[level](...args)
}
✅ 推荐:
debuginfowarn / error// 错误只上报一次
const reported = new Set()
function reportOnce(key, data) {
if (reported.has(key)) return
reported.add(key)
sendLog(data)
}
function throttleLog(fn, delay = 1000) {
let last = 0
return (...args) => {
const now = Date.now()
if (now - last < delay) return
last = now
fn(...args)
}
}
❌ 不推荐:
console.log('data', JSON.stringify(bigData))
✅ 推荐:
console.log('userId', userId)
let queue = []
function pushLog(log) {
queue.push(log)
if (queue.length >= 10) flush()
}
function flush() {
send(queue)
queue = []
}
setInterval(flush, 5000)
import pako from 'pako'
const compressed = pako.gzip(JSON.stringify(logs))
| 类型 | 存储 |
|---|---|
| 错误 | ES / ClickHouse |
| 普通 | 丢弃 / 抽样 |
| 调试 | 本地 |
const MAX = 50
logs.push(data)
if (logs.length > MAX) logs.shift()
localStorage.setItem('log', JSON.stringify(logs.slice(-100)))
| 场景 | 原因 | 对策 |
|---|---|---|
| 循环里打日志 | 高频 | 移除或节流 |
| 请求失败重试 | 日志叠加 | 只记录最终失败 |
| 大对象 JSON | 体积大 | 只记录关键字段 |
| 监听 scroll / resize | 连续触发 | 节流 |
| 第三方 SDK | 不可控 | 拦截 / 关闭 |
✅ 生产环境默认规则
✅ 开发环境
如果你能补充一下:
我可以给你一个更针对性的方案或代码模板。