74 lines
1.6 KiB
JavaScript
74 lines
1.6 KiB
JavaScript
import analytics from './index'
|
|
import { PERFORMANCE_EVENTS } from '../../constants/events'
|
|
|
|
/**
|
|
* 性能追踪器
|
|
*/
|
|
class PerformanceTracker {
|
|
constructor() {
|
|
// 页面加载开始时间
|
|
this.pageLoadStartTimes = new Map()
|
|
}
|
|
|
|
/**
|
|
* 页面开始加载
|
|
* @param {string} pagePath - 页面路径
|
|
*/
|
|
startPageLoad(pagePath) {
|
|
this.pageLoadStartTimes.set(pagePath, Date.now())
|
|
}
|
|
|
|
/**
|
|
* 页面加载完成
|
|
* @param {string} pagePath - 页面路径
|
|
*/
|
|
endPageLoad(pagePath) {
|
|
const startTime = this.pageLoadStartTimes.get(pagePath)
|
|
if (!startTime) return
|
|
|
|
const loadTime = Date.now() - startTime
|
|
this.pageLoadStartTimes.delete(pagePath)
|
|
|
|
analytics.track(PERFORMANCE_EVENTS.PAGE_LOAD_PERFORMANCE, {
|
|
page_path: pagePath,
|
|
load_time: loadTime,
|
|
load_time_range: this._getLoadTimeRange(loadTime),
|
|
})
|
|
}
|
|
|
|
/**
|
|
* 追踪API响应时间
|
|
* @param {object} params - 参数
|
|
*/
|
|
trackApiPerformance(params) {
|
|
const {
|
|
path,
|
|
method,
|
|
duration,
|
|
success,
|
|
} = params
|
|
|
|
analytics.track(PERFORMANCE_EVENTS.API_PERFORMANCE, {
|
|
api_path: path,
|
|
api_method: method,
|
|
response_time: duration,
|
|
response_time_range: this._getLoadTimeRange(duration),
|
|
is_success: success,
|
|
})
|
|
}
|
|
|
|
/**
|
|
* 获取加载时间范围
|
|
*/
|
|
_getLoadTimeRange(ms) {
|
|
if (ms < 500) return '0-500ms'
|
|
if (ms < 1000) return '500ms-1s'
|
|
if (ms < 2000) return '1-2s'
|
|
if (ms < 3000) return '2-3s'
|
|
if (ms < 5000) return '3-5s'
|
|
return '5s+'
|
|
}
|
|
}
|
|
|
|
// 导出单例
|
|
export default new PerformanceTracker() |