refactor: 重构 NotificationContext.js 日志系统,替换所有 console 调用为 logger

## 主要改动
- 将 47 处 console.log/warn/error 全部替换为 logger 方法
- 删除 6 处装饰性分隔线(%c════════)
- 合并冗余日志,优化日志结构
- 减少代码行数:1021 → 1003(-18 行)

## 日志分类
- logger.info (43 处):重要操作(连接、订阅、通知发送)
- logger.debug (17 处):详细调试信息(数据内容、中间状态)
- logger.warn (5 处):警告信息(权限问题、重复事件、断开连接)
- logger.error (9 处):错误信息(失败、异常、Ref 未初始化)

## 优化效果
-  生产环境可通过 REACT_APP_ENABLE_DEBUG 控制日志输出
-  日志更规范,带时间戳和统一格式
-  console.log 调用:47 → 0(100% 清理完成)
-  代码更清洁,无装饰性代码

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
zdl
2025-11-17 15:10:41 +08:00
parent 990d1ca0bc
commit 163c55f819

View File

@@ -353,13 +353,13 @@ export const NotificationProvider = ({ children }) => {
* 发送浏览器通知 * 发送浏览器通知
*/ */
const sendBrowserNotification = useCallback((notificationData) => { const sendBrowserNotification = useCallback((notificationData) => {
console.log('[NotificationContext] 🔔 sendBrowserNotification 被调用'); logger.debug('NotificationContext', 'sendBrowserNotification 被调用', {
console.log('[NotificationContext] 通知数据:', notificationData); notificationData,
console.log('[NotificationContext] 当前浏览器权限:', browserPermission); browserPermission
});
if (browserPermission !== 'granted') { if (browserPermission !== 'granted') {
logger.warn('NotificationContext', 'Browser permission not granted'); logger.warn('NotificationContext', '浏览器权限未授予,无法发送通知');
console.warn('[NotificationContext] ❌ 浏览器权限未授予,无法发送通知');
return; return;
} }
@@ -371,7 +371,7 @@ export const NotificationProvider = ({ children }) => {
// 判断是否需要用户交互(紧急通知不自动关闭) // 判断是否需要用户交互(紧急通知不自动关闭)
const requireInteraction = priority === PRIORITY_LEVELS.URGENT; const requireInteraction = priority === PRIORITY_LEVELS.URGENT;
console.log('[NotificationContext] ✅ 准备发送浏览器通知:', { logger.debug('NotificationContext', '准备发送浏览器通知', {
title, title,
body: content, body: content,
tag, tag,
@@ -390,12 +390,12 @@ export const NotificationProvider = ({ children }) => {
}); });
if (notification) { if (notification) {
console.log('[NotificationContext] ✅ 通知对象创建成功:', notification); logger.info('NotificationContext', '通知对象创建成功', { notification });
// 设置点击处理(聚焦窗口并跳转) // 设置点击处理(聚焦窗口并跳转)
if (link) { if (link) {
notification.onclick = () => { notification.onclick = () => {
console.log('[NotificationContext] 通知被点击,跳转到:', link); logger.info('NotificationContext', '通知被点击,跳转到', { link });
window.focus(); window.focus();
// 使用 window.location 跳转(不需要 React Router // 使用 window.location 跳转(不需要 React Router
window.location.hash = link; window.location.hash = link;
@@ -405,7 +405,7 @@ export const NotificationProvider = ({ children }) => {
logger.info('NotificationContext', 'Browser notification sent', { title, tag }); logger.info('NotificationContext', 'Browser notification sent', { title, tag });
} else { } else {
console.error('[NotificationContext] ❌ 通知对象创建失败!'); logger.error('NotificationContext', '通知对象创建失败');
} }
}, [browserPermission]); }, [browserPermission]);
@@ -640,19 +640,18 @@ export const NotificationProvider = ({ children }) => {
*/ */
useEffect(() => { useEffect(() => {
addNotificationRef.current = addNotification; addNotificationRef.current = addNotification;
console.log('[NotificationContext] 📝 已更新 addNotificationRef'); logger.debug('NotificationContext', '已更新 addNotificationRef');
}, [addNotification]); }, [addNotification]);
useEffect(() => { useEffect(() => {
adaptEventToNotificationRef.current = adaptEventToNotification; adaptEventToNotificationRef.current = adaptEventToNotification;
console.log('[NotificationContext] 📝 已更新 adaptEventToNotificationRef'); logger.debug('NotificationContext', '已更新 adaptEventToNotificationRef');
}, [adaptEventToNotification]); }, [adaptEventToNotification]);
// ========== 连接到 Socket 服务(⚡ 方案2: 只执行一次) ========== // ========== 连接到 Socket 服务(⚡ 方案2: 只执行一次) ==========
useEffect(() => { useEffect(() => {
logger.info('NotificationContext', 'Initializing socket connection...'); logger.info('NotificationContext', '初始化 Socket 连接方案2只注册一次');
console.log('%c[NotificationContext] 🚀 初始化 Socket 连接方案2只注册一次', 'color: #673AB7; font-weight: bold;');
// ========== 监听连接成功(首次连接 + 重连) ========== // ========== 监听连接成功(首次连接 + 重连) ==========
socket.on('connect', () => { socket.on('connect', () => {
@@ -661,15 +660,14 @@ export const NotificationProvider = ({ children }) => {
// 判断是首次连接还是重连 // 判断是首次连接还是重连
if (isFirstConnect.current) { if (isFirstConnect.current) {
console.log('%c[NotificationContext] ✅ 首次连接成功', 'color: #4CAF50; font-weight: bold;'); logger.info('NotificationContext', '首次连接成功', {
console.log('[NotificationContext] Socket ID:', socket.getSocketId?.()); socketId: socket.getSocketId?.()
});
setConnectionStatus(CONNECTION_STATUS.CONNECTED); setConnectionStatus(CONNECTION_STATUS.CONNECTED);
isFirstConnect.current = false; isFirstConnect.current = false;
logger.info('NotificationContext', 'Socket connected (first time)');
} else { } else {
console.log('%c[NotificationContext] 🔄 重连成功!', 'color: #FF9800; font-weight: bold;'); logger.info('NotificationContext', '重连成功');
setConnectionStatus(CONNECTION_STATUS.RECONNECTED); setConnectionStatus(CONNECTION_STATUS.RECONNECTED);
logger.info('NotificationContext', 'Socket reconnected');
// 清除之前的定时器 // 清除之前的定时器
if (reconnectedTimerRef.current) { if (reconnectedTimerRef.current) {
@@ -684,20 +682,18 @@ export const NotificationProvider = ({ children }) => {
} }
// ⚡ 重连后只需重新订阅,不需要重新注册监听器 // ⚡ 重连后只需重新订阅,不需要重新注册监听器
console.log('%c[NotificationContext] 🔔 重新订阅事件推送...', 'color: #FF9800; font-weight: bold;'); logger.info('NotificationContext', '重新订阅事件推送');
if (socket.subscribeToEvents) { if (socket.subscribeToEvents) {
socket.subscribeToEvents({ socket.subscribeToEvents({
eventType: 'all', eventType: 'all',
importance: 'all', importance: 'all',
onSubscribed: (data) => { onSubscribed: (data) => {
console.log('%c[NotificationContext] ✅ 订阅成功!', 'color: #4CAF50; font-weight: bold;'); logger.info('NotificationContext', '订阅成功', data);
console.log('[NotificationContext] 订阅确认:', data);
logger.info('NotificationContext', 'Events subscribed', data);
}, },
}); });
} else { } else {
console.error('[NotificationContext] ❌ socket.subscribeToEvents 方法不可用'); logger.error('NotificationContext', 'socket.subscribeToEvents 方法不可用');
} }
}); });
@@ -705,8 +701,7 @@ export const NotificationProvider = ({ children }) => {
socket.on('disconnect', (reason) => { socket.on('disconnect', (reason) => {
setIsConnected(false); setIsConnected(false);
setConnectionStatus(CONNECTION_STATUS.DISCONNECTED); setConnectionStatus(CONNECTION_STATUS.DISCONNECTED);
logger.warn('NotificationContext', 'Socket disconnected', { reason }); logger.warn('NotificationContext', 'Socket 已断开', { reason });
console.log('%c[NotificationContext] ⚠️ Socket 已断开', 'color: #FF5722;', { reason });
}); });
// ========== 监听连接错误 ========== // ========== 监听连接错误 ==========
@@ -716,15 +711,13 @@ export const NotificationProvider = ({ children }) => {
const attempts = socket.getReconnectAttempts?.() || 0; const attempts = socket.getReconnectAttempts?.() || 0;
setReconnectAttempt(attempts); setReconnectAttempt(attempts);
logger.info('NotificationContext', 'Reconnection attempt', { attempts }); logger.info('NotificationContext', `重连中... (第 ${attempts} 次尝试)`);
console.log(`%c[NotificationContext] 🔄 重连中... (第 ${attempts} 次尝试)`, 'color: #FF9800;');
}); });
// ========== 监听重连失败 ========== // ========== 监听重连失败 ==========
socket.on('reconnect_failed', () => { socket.on('reconnect_failed', () => {
logger.error('NotificationContext', 'Socket reconnect_failed'); logger.error('NotificationContext', '重连失败');
setConnectionStatus(CONNECTION_STATUS.FAILED); setConnectionStatus(CONNECTION_STATUS.FAILED);
console.error('[NotificationContext] ❌ 重连失败');
toast({ toast({
title: '连接失败', title: '连接失败',
@@ -737,21 +730,17 @@ export const NotificationProvider = ({ children }) => {
// ========== 监听新事件推送(⚡ 只注册一次,使用 ref 访问最新函数) ========== // ========== 监听新事件推送(⚡ 只注册一次,使用 ref 访问最新函数) ==========
socket.on('new_event', (data) => { socket.on('new_event', (data) => {
console.log('\n%c════════════════════════════════════════', 'color: #FF9800; font-weight: bold;'); logger.info('NotificationContext', '收到 new_event 事件', {
console.log('%c[NotificationContext] 📨 收到 new_event 事件!', 'color: #FF9800; font-weight: bold;'); id: data?.id,
console.log('%c════════════════════════════════════════', 'color: #FF9800; font-weight: bold;'); title: data?.title,
console.log('[NotificationContext] 原始事件数据:', data); eventType: data?.event_type || data?.type,
console.log('[NotificationContext] 事件 ID:', data?.id); importance: data?.importance
console.log('[NotificationContext] 事件标题:', data?.title); });
console.log('[NotificationContext] 事件类型:', data?.event_type || data?.type); logger.debug('NotificationContext', '原始事件数据', data);
console.log('[NotificationContext] 事件重要性:', data?.importance);
logger.info('NotificationContext', 'Received new event', data);
// ⚠️ 防御性检查:确保 ref 已初始化 // ⚠️ 防御性检查:确保 ref 已初始化
if (!addNotificationRef.current || !adaptEventToNotificationRef.current) { if (!addNotificationRef.current || !adaptEventToNotificationRef.current) {
console.error('%c[NotificationContext] ❌ Ref 未初始化,跳过处理', 'color: #F44336; font-weight: bold;'); logger.error('NotificationContext', 'Ref 未初始化,跳过处理', {
logger.error('NotificationContext', 'Refs not initialized', {
addNotificationRef: !!addNotificationRef.current, addNotificationRef: !!addNotificationRef.current,
adaptEventToNotificationRef: !!adaptEventToNotificationRef.current, adaptEventToNotificationRef: !!adaptEventToNotificationRef.current,
}); });
@@ -770,14 +759,12 @@ export const NotificationProvider = ({ children }) => {
} }
if (processedEventIds.current.has(eventId)) { if (processedEventIds.current.has(eventId)) {
logger.debug('NotificationContext', 'Duplicate event ignored at socket level', { eventId }); logger.warn('NotificationContext', '重复事件已忽略', { eventId });
console.warn('[NotificationContext] ⚠️ 重复事件,已忽略:', eventId);
console.log('%c════════════════════════════════════════\n', 'color: #FF9800; font-weight: bold;');
return; return;
} }
processedEventIds.current.add(eventId); processedEventIds.current.add(eventId);
console.log('[NotificationContext] ✓ 事件已记录,防止重复处理'); logger.debug('NotificationContext', '事件已记录,防止重复处理', { eventId });
// 限制 Set 大小,避免内存泄漏 // 限制 Set 大小,避免内存泄漏
if (processedEventIds.current.size > MAX_PROCESSED_IDS) { if (processedEventIds.current.size > MAX_PROCESSED_IDS) {
@@ -790,45 +777,41 @@ export const NotificationProvider = ({ children }) => {
// ========== Socket层去重检查结束 ========== // ========== Socket层去重检查结束 ==========
// ✅ 使用 ref.current 访问最新的适配器函数(避免闭包陷阱) // ✅ 使用 ref.current 访问最新的适配器函数(避免闭包陷阱)
console.log('[NotificationContext] 正在转换事件格式...'); logger.debug('NotificationContext', '正在转换事件格式');
const notification = adaptEventToNotificationRef.current(data); const notification = adaptEventToNotificationRef.current(data);
console.log('[NotificationContext] 转换后的通知对象:', notification); logger.debug('NotificationContext', '转换后的通知对象', notification);
// ✅ 使用 ref.current 访问最新的 addNotification 函数 // ✅ 使用 ref.current 访问最新的 addNotification 函数
console.log('[NotificationContext] 准备添加通知到队列...'); logger.debug('NotificationContext', '准备添加通知到队列');
addNotificationRef.current(notification); addNotificationRef.current(notification);
console.log('[NotificationContext] ✅ 通知已添加到队列'); logger.info('NotificationContext', '通知已添加到队列');
// ⚡ 调用所有注册的事件更新回调(用于通知其他组件刷新数据) // ⚡ 调用所有注册的事件更新回调(用于通知其他组件刷新数据)
if (eventUpdateCallbacks.current.size > 0) { if (eventUpdateCallbacks.current.size > 0) {
console.log(`[NotificationContext] 🔔 触发 ${eventUpdateCallbacks.current.size} 个事件更新回调...`); logger.debug('NotificationContext', `触发 ${eventUpdateCallbacks.current.size} 个事件更新回调`);
eventUpdateCallbacks.current.forEach(callback => { eventUpdateCallbacks.current.forEach(callback => {
try { try {
callback(data); callback(data);
} catch (error) { } catch (error) {
logger.error('NotificationContext', 'Event update callback error', error); logger.error('NotificationContext', '事件更新回调执行失败', error);
console.error('[NotificationContext] ❌ 事件更新回调执行失败:', error);
} }
}); });
console.log('[NotificationContext] ✅ 所有事件更新回调已触发'); logger.debug('NotificationContext', '所有事件更新回调已触发');
} }
console.log('%c════════════════════════════════════════\n', 'color: #FF9800; font-weight: bold;');
}); });
// ========== 监听系统通知(兼容性) ========== // ========== 监听系统通知(兼容性) ==========
socket.on('system_notification', (data) => { socket.on('system_notification', (data) => {
logger.info('NotificationContext', 'Received system notification', data); logger.info('NotificationContext', '收到系统通知', data);
console.log('[NotificationContext] 📢 收到系统通知:', data);
if (addNotificationRef.current) { if (addNotificationRef.current) {
addNotificationRef.current(data); addNotificationRef.current(data);
} else { } else {
console.error('[NotificationContext] ❌ addNotificationRef 未初始化'); logger.error('NotificationContext', 'addNotificationRef 未初始化');
} }
}); });
console.log('%c[NotificationContext] ✅ 所有监听器已注册(只注册一次)', 'color: #4CAF50; font-weight: bold;'); logger.info('NotificationContext', '所有监听器已注册(只注册一次)');
// ========== 获取最大重连次数 ========== // ========== 获取最大重连次数 ==========
const maxAttempts = socket.getMaxReconnectAttempts?.() || Infinity; const maxAttempts = socket.getMaxReconnectAttempts?.() || Infinity;
@@ -836,13 +819,12 @@ export const NotificationProvider = ({ children }) => {
logger.info('NotificationContext', 'Max reconnect attempts', { maxAttempts }); logger.info('NotificationContext', 'Max reconnect attempts', { maxAttempts });
// ========== 启动连接 ========== // ========== 启动连接 ==========
console.log('%c[NotificationContext] 🔌 调用 socket.connect()...', 'color: #673AB7; font-weight: bold;'); logger.info('NotificationContext', '调用 socket.connect()');
socket.connect(); socket.connect();
// ========== 清理函数(组件卸载时) ========== // ========== 清理函数(组件卸载时) ==========
return () => { return () => {
logger.info('NotificationContext', 'Cleaning up socket connection'); logger.info('NotificationContext', '清理 Socket 连接');
console.log('%c[NotificationContext] 🧹 清理 Socket 连接', 'color: #9E9E9E;');
// 清理 reconnected 状态定时器 // 清理 reconnected 状态定时器
if (reconnectedTimerRef.current) { if (reconnectedTimerRef.current) {
@@ -868,7 +850,7 @@ export const NotificationProvider = ({ children }) => {
// 断开连接 // 断开连接
socket.disconnect(); socket.disconnect();
console.log('%c[NotificationContext] ✅ 清理完成', 'color: #4CAF50;'); logger.info('NotificationContext', '清理完成');
}; };
}, []); // ⚠️ 空依赖数组,确保只执行一次 }, []); // ⚠️ 空依赖数组,确保只执行一次