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