1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
| // 性能监控SDK
class PerformanceSDK {
constructor(config) {
this.config = {
apiKey: config.apiKey,
endpoint: config.endpoint,
enableCrashReporting: config.enableCrashReporting || true,
enableANRReporting: config.enableANRReporting || true,
enableNetworkMonitoring: config.enableNetworkMonitoring || true,
enableMemoryLeakDetection: config.enableMemoryLeakDetection || true,
sampleRate: config.sampleRate || 1.0
};
this.metrics = {
fps: [],
memory: [],
network: [],
crashes: [],
anr: []
};
this.isInitialized = false;
}
// 初始化SDK
async initialize() {
if (this.isInitialized) return;
try {
// 设置全局错误处理
if (this.config.enableCrashReporting) {
this.setupCrashReporting();
}
// 设置ANR监控
if (this.config.enableANRReporting) {
this.setupANRMonitoring();
}
// 设置网络监控
if (this.config.enableNetworkMonitoring) {
this.setupNetworkMonitoring();
}
// 设置内存泄漏检测
if (this.config.enableMemoryLeakDetection) {
this.setupMemoryLeakDetection();
}
this.isInitialized = true;
console.log('Performance SDK initialized');
} catch (error) {
console.error('Failed to initialize Performance SDK:', error);
}
}
// 设置崩溃报告
setupCrashReporting() {
const defaultErrorHandler = ErrorUtils.getGlobalHandler();
ErrorUtils.setGlobalHandler((error, isFatal) => {
// 记录崩溃信息
const crashInfo = {
message: error.message,
stack: error.stack,
isFatal,
timestamp: Date.now(),
deviceInfo: this.getDeviceInfo(),
appState: this.getAppState()
};
this.metrics.crashes.push(crashInfo);
// 上报崩溃
this.reportCrash(crashInfo);
// 调用原始错误处理器
defaultErrorHandler(error, isFatal);
});
}
// 设置ANR监控
setupANRMonitoring() {
let isChecking = false;
const checkANR = () => {
if (isChecking) return;
isChecking = true;
const startTime = Date.now();
// 使用setTimeout检测阻塞
setTimeout(() => {
const endTime = Date.now();
const duration = endTime - startTime;
// 如果执行时间超过2秒,认为是ANR
if (duration > 2000) {
const anrInfo = {
duration,
timestamp: Date.now(),
stackTrace: this.getCurrentStackTrace(),
deviceInfo: this.getDeviceInfo()
};
this.metrics.anr.push(anrInfo);
this.reportANR(anrInfo);
}
isChecking = false;
}, 100);
};
// 定期检查
setInterval(checkANR, 1000);
}
// 设置网络监控
setupNetworkMonitoring() {
const originalFetch = global.fetch;
global.fetch = async (...args) => {
const startTime = Date.now();
const [url, options] = args;
try {
const response = await originalFetch(...args);
const endTime = Date.now();
// 记录网络请求
const networkMetric = {
url,
method: options?.method || 'GET',
status: response.status,
duration: endTime - startTime,
size: response.headers.get('content-length'),
timestamp: endTime
};
this.metrics.network.push(networkMetric);
this.reportNetworkMetric(networkMetric);
return response;
} catch (error) {
const endTime = Date.now();
// 记录网络错误
const networkMetric = {
url,
method: options?.method || 'GET',
error: error.message,
duration: endTime - startTime,
timestamp: endTime
};
this.metrics.network.push(networkMetric);
this.reportNetworkMetric(networkMetric);
throw error;
}
};
}
// 设置内存泄漏检测
setupMemoryLeakDetection() {
let lastMemoryUsage = 0;
let leakCount = 0;
setInterval(() => {
const currentMemoryUsage = this.getMemoryUsage();
if (lastMemoryUsage > 0) {
const memoryIncrease = currentMemoryUsage - lastMemoryUsage;
// 如果内存持续增长,可能存在内存泄漏
if (memoryIncrease > 10 * 1024 * 1024) { // 10MB
leakCount++;
if (leakCount >= 3) {
const leakInfo = {
currentUsage: currentMemoryUsage,
increase: memoryIncrease,
leakCount,
timestamp: Date.now()
};
this.reportMemoryLeak(leakInfo);
leakCount = 0;
}
} else {
leakCount = 0;
}
}
lastMemoryUsage = currentMemoryUsage;
this.metrics.memory.push({
usage: currentMemoryUsage,
timestamp: Date.now()
});
}, 30000); // 每30秒检查一次
}
// 记录自定义指标
recordMetric(name, value, tags = {}) {
const metric = {
name,
value,
tags,
timestamp: Date.now()
};
// 根据指标类型分类
if (name.startsWith('fps.')) {
this.metrics.fps.push(metric);
}
this.reportCustomMetric(metric);
}
// 记录FPS
recordFPS(fps) {
this.recordMetric('fps.current', fps);
if (fps < 30) {
this.recordMetric('fps.low_fps', 1, { fps_range: '0-30' });
} else if (fps < 45) {
this.recordMetric('fps.low_fps', 1, { fps_range: '30-45' });
}
}
// 记录屏幕性能
recordScreenPerformance(screenName, metrics) {
this.recordMetric(`screen.${screenName}.load_time`, metrics.loadTime);
this.recordMetric(`screen.${screenName}.render_time`, metrics.renderTime);
if (metrics.interactionTime) {
this.recordMetric(`screen.${screenName}.interaction_time`, metrics.interactionTime);
}
}
// 获取设备信息
getDeviceInfo() {
return {
platform: Platform.OS,
version: Platform.Version,
brand: DeviceInfo.getBrand(),
model: DeviceInfo.getModel(),
systemVersion: DeviceInfo.getSystemVersion(),
appVersion: DeviceInfo.getVersion(),
buildNumber: DeviceInfo.getBuildNumber(),
bundleId: DeviceInfo.getBundleId(),
isEmulator: DeviceInfo.isEmulatorSync()
};
}
// 获取应用状态
getAppState() {
return {
state: AppState.currentState,
memoryUsage: this.getMemoryUsage(),
storageUsage: this.getStorageUsage()
};
}
// 获取内存使用情况
getMemoryUsage() {
if (Platform.OS === 'android') {
return require('react-native').NativeModules.MemoryInfoModule.getMemoryUsage();
} else {
return require('react-native').NativeModules.MemoryModule.getMemoryUsage();
}
}
// 获取存储使用情况
getStorageUsage() {
// 实现存储使用情况获取
return {
used: 0,
total: 0
};
}
// 获取当前堆栈跟踪
getCurrentStackTrace() {
// 实现堆栈跟踪获取
return new Error().stack;
}
// 上报崩溃
reportCrash(crashInfo) {
this.sendToEndpoint('/crashes', crashInfo);
}
// 上报ANR
reportANR(anrInfo) {
this.sendToEndpoint('/anr', anrInfo);
}
// 上报网络指标
reportNetworkMetric(networkMetric) {
this.sendToEndpoint('/network', networkMetric);
}
// 上报内存泄漏
reportMemoryLeak(leakInfo) {
this.sendToEndpoint('/memory-leaks', leakInfo);
}
// 上报自定义指标
reportCustomMetric(metric) {
this.sendToEndpoint('/metrics', metric);
}
// 发送到端点
async sendToEndpoint(path, data) {
if (Math.random() > this.config.sampleRate) return;
try {
await fetch(`${this.config.endpoint}${path}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': this.config.apiKey
},
body: JSON.stringify({
...data,
deviceInfo: this.getDeviceInfo(),
sessionId: this.getSessionId()
})
});
} catch (error) {
console.error('Failed to report to endpoint:', error);
}
}
// 获取会话ID
getSessionId() {
let sessionId = require('react-native').AsyncStorage.getItem('performance_session_id');
if (!sessionId) {
sessionId = Date.now().toString(36) + Math.random().toString(36).substr(2);
require('react-native').AsyncStorage.setItem('performance_session_id', sessionId);
}
return sessionId;
}
// 生成性能报告
generateReport() {
const report = {
timeRange: {
start: Date.now() - 24 * 60 * 60 * 1000, // 24小时前
end: Date.now()
},
summary: {
totalCrashes: this.metrics.crashes.length,
totalANR: this.metrics.anr.length,
avgFPS: this.calculateAverageFPS(),
avgMemoryUsage: this.calculateAverageMemory(),
networkErrorRate: this.calculateNetworkErrorRate()
},
details: {
crashes: this.metrics.crashes.slice(-10),
anr: this.metrics.anr.slice(-10),
networkErrors: this.metrics.network.filter(m => m.error).slice(-20)
}
};
return report;
}
// 计算平均FPS
calculateAverageFPS() {
const recentFPS = this.metrics.fps.slice(-100);
if (recentFPS.length === 0) return 60;
const total = recentFPS.reduce((sum, metric) => sum + metric.value, 0);
return Math.round(total / recentFPS.length);
}
// 计算平均内存使用
calculateAverageMemory() {
const recentMemory = this.metrics.memory.slice(-50);
if (recentMemory.length === 0) return 0;
const total = recentMemory.reduce((sum, metric) => sum + metric.usage, 0);
return Math.round(total / recentMemory.length);
}
// 计算网络错误率
calculateNetworkErrorRate() {
const recentNetwork = this.metrics.network.slice(-100);
if (recentNetwork.length === 0) return 0;
const errors = recentNetwork.filter(m => m.error).length;
return Math.round((errors / recentNetwork.length) * 100);
}
}
// 使用示例
const performanceSDK = new PerformanceSDK({
apiKey: 'your-api-key',
endpoint: 'https://your-performance-endpoint.com/api/v1',
sampleRate: 0.1 // 10%采样率
});
// 在应用启动时初始化
performanceSDK.initialize();
// 在组件中使用
const MyComponent = () => {
useEffect(() => {
// 记录屏幕性能
const startTime = Date.now();
// 模拟渲染时间
setTimeout(() => {
const renderTime = Date.now() - startTime;
performanceSDK.recordScreenPerformance('MyComponent', {
loadTime: startTime - performance.mark('component_start'),
renderTime
});
}, 0);
// 记录FPS
const fpsInterval = setInterval(() => {
performanceSDK.recordFPS(58); // 示例FPS值
}, 1000);
return () => {
clearInterval(fpsInterval);
};
}, []);
return <View>My Component</View>;
};
|