Reduce noisy runtime logging in frontend flows.

This keeps chat, notification, and post interactions cleaner in production while preserving error-level visibility.
This commit is contained in:
2026-03-09 22:18:47 +08:00
parent 3968660048
commit 63e32b15a3
21 changed files with 14 additions and 284 deletions

View File

@@ -46,12 +46,9 @@ let appStateSubscription: any = null;
// 定义后台任务
TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
console.log('[BackgroundService] 后台任务执行中...');
try {
// 检查 WebSocket 连接状态
if (!websocketService.isConnected()) {
console.log('[BackgroundService] WebSocket 断开,尝试重连');
await websocketService.connect();
}
@@ -65,11 +62,8 @@ TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
// WebSocket 保活任务
TaskManager.defineTask(WEBSOCKET_KEEPALIVE_TASK, async () => {
console.log('[BackgroundService] WebSocket 保活任务执行...');
try {
if (!websocketService.isConnected()) {
console.log('[BackgroundService] WebSocket 断开,尝试重连');
await websocketService.connect();
}
return BackgroundFetch.BackgroundFetchResult.NewData;
@@ -178,7 +172,6 @@ async function registerBackgroundTasks(): Promise<void> {
stopOnTerminate: false, // App 终止后继续运行
startOnBoot: true, // 设备启动后自动运行
});
console.log('[BackgroundService] 后台任务注册成功');
}
// 注册 WebSocket 保活任务
@@ -189,7 +182,6 @@ async function registerBackgroundTasks(): Promise<void> {
stopOnTerminate: false,
startOnBoot: true,
});
console.log('[BackgroundService] WebSocket 保活任务注册成功');
}
} catch (error) {
console.error('[BackgroundService] 注册后台任务失败:', error);
@@ -203,7 +195,6 @@ async function unregisterBackgroundTasks(): Promise<void> {
try {
await BackgroundFetch.unregisterTaskAsync(BACKGROUND_FETCH_TASK);
await BackgroundFetch.unregisterTaskAsync(WEBSOCKET_KEEPALIVE_TASK);
console.log('[BackgroundService] 后台任务已取消');
} catch (error) {
console.error('[BackgroundService] 取消后台任务失败:', error);
}
@@ -218,17 +209,12 @@ function setupAppStateListener(): void {
}
appStateSubscription = AppState.addEventListener('change', (nextAppState: AppStateStatus) => {
console.log('[BackgroundService] App 状态变化:', nextAppState);
void nextAppState;
if (nextAppState === 'active') {
// App 回到前台,确保连接
console.log('[BackgroundService] App 回到前台');
if (!websocketService.isConnected()) {
websocketService.connect();
}
} else if (nextAppState === 'background') {
// App 进入后台,启动保活
console.log('[BackgroundService] App 进入后台,启动保活机制');
}
});
}
@@ -238,13 +224,10 @@ function setupAppStateListener(): void {
*/
export async function initBackgroundService(): Promise<boolean> {
if (isInitialized) {
console.log('[BackgroundService] 服务已初始化');
return true;
}
try {
console.log('[BackgroundService] 初始化后台保活服务...');
// 检查后台任务状态
const status = await BackgroundFetch.getStatusAsync();
if (status !== BackgroundFetch.BackgroundFetchStatus.Available) {
@@ -259,7 +242,6 @@ export async function initBackgroundService(): Promise<boolean> {
setupAppStateListener();
isInitialized = true;
console.log('[BackgroundService] 后台保活服务初始化完成');
return true;
} catch (error) {
console.error('[BackgroundService] 初始化失败:', error);
@@ -280,7 +262,6 @@ export async function stopBackgroundService(): Promise<void> {
}
isInitialized = false;
console.log('[BackgroundService] 后台保活服务已停止');
} catch (error) {
console.error('[BackgroundService] 停止服务失败:', error);
}

View File

@@ -35,19 +35,16 @@ export const initDatabase = async (userId?: string): Promise<void> => {
// 如果存在旧的数据库连接且用户ID变化需要关闭旧连接
if (db && currentDbUserId !== userId) {
console.log(`[Database] 切换用户数据库: ${currentDbUserId} -> ${userId}`);
await closeDatabase();
}
// 如果已经打开了正确的数据库,直接返回
if (db && currentDbUserId === userId) {
console.log(`[Database] 数据库已初始化: ${dbName}`);
return;
}
db = await SQLite.openDatabaseAsync(dbName);
currentDbUserId = userId || null;
console.log(`[Database] 打开数据库: ${dbName}`);
// 创建消息表(包含新字段 seq, status, segments
await db.execAsync(`
@@ -153,7 +150,6 @@ export const initDatabase = async (userId?: string): Promise<void> => {
CREATE INDEX IF NOT EXISTS idx_messages_conversation_seq ON messages(conversationId, seq);
`);
console.log('数据库初始化成功');
} catch (error) {
console.error('数据库初始化失败:', error);
throw error;
@@ -167,7 +163,6 @@ export const closeDatabase = async (): Promise<void> => {
if (db) {
try {
await db.closeAsync();
console.log('[Database] 数据库连接已关闭');
} catch (error) {
console.error('[Database] 关闭数据库失败:', error);
}
@@ -198,19 +193,16 @@ const migrateDatabase = async (): Promise<void> => {
// 添加 seq 列
if (!columns.includes('seq')) {
await database.execAsync(`ALTER TABLE messages ADD COLUMN seq INTEGER DEFAULT 0`);
console.log('数据库迁移:添加 seq 列');
}
// 添加 status 列
if (!columns.includes('status')) {
await database.execAsync(`ALTER TABLE messages ADD COLUMN status TEXT DEFAULT 'normal'`);
console.log('数据库迁移:添加 status 列');
}
// 添加 segments 列(用于存储消息的 segments JSON
if (!columns.includes('segments')) {
await database.execAsync(`ALTER TABLE messages ADD COLUMN segments TEXT`);
console.log('数据库迁移:添加 segments 列');
}
// 检查 conversations 表是否有 lastSeq 列
@@ -221,7 +213,6 @@ const migrateDatabase = async (): Promise<void> => {
if (!convColumns.includes('lastSeq')) {
await database.execAsync(`ALTER TABLE conversations ADD COLUMN lastSeq INTEGER DEFAULT 0`);
console.log('数据库迁移:添加 lastSeq 列');
}
} catch (error) {
console.error('数据库迁移失败:', error);

View File

@@ -130,11 +130,8 @@ class PostService {
// 点赞帖子
async likePost(postId: string): Promise<Post | null> {
try {
console.log('[postService] likePost called, postId:', postId);
const response = await api.post<Post>(`/posts/${postId}/like`);
console.log('[postService] likePost response:', response);
if (response.code === 0) {
console.log('[postService] likePost success, data:', response.data);
return response.data;
}
console.warn('[postService] likePost failed, code:', response.code);
@@ -148,11 +145,8 @@ class PostService {
// 取消点赞帖子
async unlikePost(postId: string): Promise<Post | null> {
try {
console.log('[postService] unlikePost called, postId:', postId);
const response = await api.delete<Post>(`/posts/${postId}/like`);
console.log('[postService] unlikePost response:', response);
if (response.code === 0) {
console.log('[postService] unlikePost success, data:', response.data);
return response.data;
}
console.warn('[postService] unlikePost failed, code:', response.code);
@@ -166,11 +160,8 @@ class PostService {
// 收藏帖子
async favoritePost(postId: string): Promise<Post | null> {
try {
console.log('[postService] favoritePost called, postId:', postId);
const response = await api.post<Post>(`/posts/${postId}/favorite`);
console.log('[postService] favoritePost response:', response);
if (response.code === 0) {
console.log('[postService] favoritePost success, data:', response.data);
return response.data;
}
console.warn('[postService] favoritePost failed, code:', response.code);
@@ -184,11 +175,8 @@ class PostService {
// 取消收藏帖子
async unfavoritePost(postId: string): Promise<Post | null> {
try {
console.log('[postService] unfavoritePost called, postId:', postId);
const response = await api.delete<Post>(`/posts/${postId}/favorite`);
console.log('[postService] unfavoritePost response:', response);
if (response.code === 0) {
console.log('[postService] unfavoritePost success, data:', response.data);
return response.data;
}
console.warn('[postService] unfavoritePost failed, code:', response.code);

View File

@@ -73,7 +73,6 @@ export const addStickerFromUrl = async (
return response.data.sticker;
} catch (error: any) {
if (error.response?.status === 409) {
console.log('表情已存在');
return null;
}
console.error('添加自定义表情失败:', error);

View File

@@ -68,7 +68,6 @@ class SystemNotificationService {
}
if (finalStatus !== 'granted') {
console.log('[SystemNotification] 通知权限未授权');
return false;
}
@@ -100,7 +99,6 @@ class SystemNotificationService {
});
this.isInitialized = true;
console.log('[SystemNotification] 通知服务初始化成功');
return true;
} catch (error) {
console.error('[SystemNotification] 初始化失败:', error);
@@ -138,7 +136,6 @@ class SystemNotificationService {
trigger: null, // null 表示立即显示
});
console.log('[SystemNotification] 通知已显示:', notificationId);
return notificationId;
} catch (error) {
console.error('[SystemNotification] 显示通知失败:', error);
@@ -182,23 +179,20 @@ class SystemNotificationService {
}
async handleWSMessage(message: WSChatMessage | WSNotificationMessage | WSAnnouncementMessage): Promise<void> {
console.log('[SystemNotification] handleWSMessage 被调用, 当前AppState:', this.currentAppState);
// 仅在后台时显示通知,前台时不显示(用户正在使用应用,可以直接看到消息)
if (this.currentAppState !== 'active') {
// 判断是否是聊天消息(通过 segments 字段)
if ('segments' in message) {
const chatMsg = message as WSChatMessage;
const body = extractTextFromSegments(chatMsg.segments);
console.log('[SystemNotification] 后台模式 - 显示聊天通知:', chatMsg.id, body);
void chatMsg;
void body;
await this.showChatNotification(chatMsg);
} else {
const notifMsg = message as WSNotificationMessage | WSAnnouncementMessage;
console.log('[SystemNotification] 后台模式 - 显示系统通知:', notifMsg.id, notifMsg.content);
void notifMsg;
await this.showWSNotification(notifMsg);
}
} else {
console.log('[SystemNotification] 前台模式 - 不显示通知');
}
}

View File

@@ -293,7 +293,6 @@ class WebSocketService {
// 连接 WebSocket
async connect(): Promise<boolean> {
if (this.socket?.readyState === WebSocket.OPEN || this.isConnecting) {
console.log('WebSocket 已经在连接中或已连接');
return true;
}
@@ -317,7 +316,6 @@ class WebSocketService {
// 设置事件处理器
this.socket.onopen = () => {
console.log('WebSocket 连接成功');
this.isConnecting = false;
this.reconnectAttempts = 0;
this.startHeartbeat();
@@ -336,12 +334,10 @@ class WebSocketService {
this.socket.onerror = () => {
// 静默处理错误,不打印完整错误对象
// WebSocket 错误通常会在 onclose 中处理,这里只标记状态
console.log('[WebSocket] 连接出现错误,将在 onclose 中处理重连');
this.isConnecting = false;
};
this.socket.onclose = (event) => {
console.log('[WebSocket] 连接关闭, code:', event.code, 'reason:', event.reason || '未知');
this.isConnecting = false;
this.stopHeartbeat();
@@ -425,7 +421,6 @@ class WebSocketService {
},
};
this.socket.send(JSON.stringify(payload));
console.log('[WebSocket] 发送消息 (新格式):', JSON.stringify(payload));
return true;
} catch (error) {
console.error('发送 WebSocket 消息失败:', error);
@@ -464,7 +459,6 @@ class WebSocketService {
private handleMessage(rawMessage: any): void {
// 忽略心跳消息的日志,减少噪音
if (rawMessage.type !== 'ping' && rawMessage.type !== 'pong') {
console.log('[WebSocket] 收到消息:', JSON.stringify(rawMessage));
}
// 处理心跳消息 - 不需要特殊处理,只需不报错
@@ -475,17 +469,14 @@ private handleMessage(rawMessage: any): void {
// 统一处理所有消息类型:后端发送格式为 { type, data },需要提取 data 字段
let message = rawMessage;
if (rawMessage.data) {
console.log('[WebSocket] 提取 data 字段, type:', rawMessage.type);
message = {
type: rawMessage.type,
...rawMessage.data, // 将 data 的内容展开到顶层
};
console.log('[WebSocket] 转换后的消息:', JSON.stringify(message));
}
// 检测新事件格式:通过 detail_type 字段判断
if (message.detail_type && (message.type === 'message' || message.type === 'notice' || message.type === 'request' || message.type === 'meta')) {
console.log('[WebSocket] 检测到新事件格式, type:', message.type, 'detail_type:', message.detail_type);
this.handleNewEventFormat(message);
return;
}
@@ -496,11 +487,8 @@ private handleMessage(rawMessage: any): void {
// 如果有 group_id说明这是后端同时发送的群聊消息旧格式帧忽略它
// 群聊消息会通过另一帧 type:'group_message' 到达,那里有完整的 sender_id
if (message.group_id) {
console.log('[WebSocket] 忽略群聊消息的 message 格式帧,等待 group_message 帧:', message.id);
return;
}
console.log('[WebSocket] 收到 message 类型消息');
console.log('[WebSocket] 原始消息:', JSON.stringify(message));
// 解析 segments只支持 segments 字段)
let segments = message.segments;
@@ -512,7 +500,6 @@ private handleMessage(rawMessage: any): void {
}
}
console.log('[WebSocket] segments:', JSON.stringify(segments));
// 转换为前端 WSChatMessage 格式
const chatMessage: WSChatMessage = {
@@ -528,7 +515,6 @@ private handleMessage(rawMessage: any): void {
// 调用 chat 类型的处理器
const handlers = this.messageHandlers.get('chat');
if (handlers) {
console.log('[WebSocket] 转换 message -> chat, 处理器数量:', handlers.length);
handlers.forEach(handler => handler(chatMessage));
}
@@ -538,7 +524,6 @@ private handleMessage(rawMessage: any): void {
});
// 收到聊天消息时也调用系统通知服务
console.log('[WebSocket] 收到聊天消息,调用系统通知服务');
systemNotificationService.handleWSMessage(chatMessage).catch(err => {
console.error('[WebSocket] 聊天消息通知显示失败:', err);
});
@@ -548,7 +533,6 @@ private handleMessage(rawMessage: any): void {
// 处理 "read" 已读回执消息 - 转换格式后路由到处理器
if (message.type === 'read') {
console.log('[WebSocket] 收到 read 类型消息');
const readHandlers = this.messageHandlers.get('read');
if (readHandlers) {
// 转换为前端期望的格式保持string类型
@@ -559,7 +543,6 @@ private handleMessage(rawMessage: any): void {
user_id: message.user_id || message.userId,
seq: typeof message.seq === 'string' ? parseInt(message.seq, 10) : message.seq,
};
console.log('[WebSocket] 转换 read 消息, handlers数量:', readHandlers.length);
readHandlers.forEach(handler => handler(readMessage));
}
return;
@@ -573,7 +556,6 @@ private handleMessage(rawMessage: any): void {
try {
const parsedSegments = JSON.parse(message.segments);
processedMessage = { ...message, segments: parsedSegments };
console.log('[WebSocket] 解析 group_message segments 成功:', JSON.stringify(parsedSegments));
} catch (e) {
console.error('[WebSocket] 解析 group_message segments 失败:', e);
}
@@ -581,26 +563,21 @@ private handleMessage(rawMessage: any): void {
const handlers = this.messageHandlers.get(message.type);
if (handlers) {
console.log('[WebSocket] 找到处理器,数量:', handlers.length, '类型:', message.type);
// 针对群聊消息和群通知添加详细日志
if (message.type === 'group_message') {
console.log('[WebSocket] 群聊消息详情:', JSON.stringify(processedMessage, null, 2));
// 收到群聊消息时触发震动
vibrateOnMessage('group_message').catch(err => {
console.error('[WebSocket] 群聊消息震动反馈失败:', err);
});
}
if (message.type === 'group_notice') {
console.log('[WebSocket] 群通知详情:', JSON.stringify(message, null, 2));
}
handlers.forEach(handler => handler(processedMessage));
} else {
console.log('[WebSocket] 未找到处理器,类型:', message.type, '可用类型:', Array.from(this.messageHandlers.keys()));
}
// 处理通知和公告消息时调用系统通知服务
if (message.type === 'notification' || message.type === 'announcement') {
console.log('[WebSocket] 收到通知/公告消息,调用系统通知服务');
// 收到通知时触发震动
vibrateOnMessage('notification').catch(err => {
console.error('[WebSocket] 通知震动反馈失败:', err);
@@ -615,7 +592,6 @@ private handleMessage(rawMessage: any): void {
private handleNewEventFormat(message: any): void {
const { type, detail_type, id, time, seq, message: segments, conversation_id, user_id } = message;
console.log('[WebSocket] 处理新事件格式:', { type, detail_type, id, time, seq, conversation_id, user_id });
// 根据 type 和 detail_type 路由消息
switch (type) {
@@ -642,7 +618,6 @@ private handleNewEventFormat(message: any): void {
break;
default:
console.log('[WebSocket] 未知事件类型:', type);
}
}
@@ -670,7 +645,6 @@ private handleNewMessageEvent(message: any): void {
const groupHandlers = this.messageHandlers.get('group_message');
if (groupHandlers) {
console.log('[WebSocket] 新格式群聊消息事件, 处理器数量:', groupHandlers.length);
groupHandlers.forEach(handler => handler(groupChatMessage));
}
@@ -695,7 +669,6 @@ private handleNewMessageEvent(message: any): void {
const chatHandlers = this.messageHandlers.get('chat');
if (chatHandlers) {
console.log('[WebSocket] 新格式私聊消息事件, 处理器数量:', chatHandlers.length);
chatHandlers.forEach(handler => handler(chatMessage));
}
@@ -713,7 +686,6 @@ private handleNewMessageEvent(message: any): void {
private handleNewNoticeEvent(message: any): void {
const { detail_type, id, time, user_id, message: segments } = message;
console.log('[WebSocket] 收到新格式通知事件, detail_type:', detail_type, 'user_id:', user_id);
// 调用 notice 类型的处理器
const handlers = this.messageHandlers.get('notice');
@@ -734,7 +706,6 @@ private handleNewNoticeEvent(message: any): void {
private handleNewRequestEvent(message: any): void {
const { detail_type, id, time, user_id, message: segments } = message;
console.log('[WebSocket] 收到新格式请求事件, detail_type:', detail_type, 'user_id:', user_id);
// 调用 request 类型的处理器
const handlers = this.messageHandlers.get('request');
@@ -755,12 +726,10 @@ private handleNewRequestEvent(message: any): void {
private handleNewMetaEvent(message: any): void {
const { detail_type, id, time, conversation_id, user_id, seq } = message;
console.log('[WebSocket] 收到新格式元事件, detail_type:', detail_type);
switch (detail_type) {
case 'heartbeat':
// 心跳事件,不需要特殊处理
console.log('[WebSocket] 收到心跳');
break;
case 'typing':
@@ -793,8 +762,6 @@ private handleNewMetaEvent(message: any): void {
case 'ack':
// 消息发送确认事件 - 转换为对应消息格式并路由到处理器
console.log('[WebSocket][DEBUG] 收到 ack 确认消息, 完整消息:', JSON.stringify(message));
console.log('[WebSocket][DEBUG] ack 消息字段: id=', message.id, 'group_id=', message.group_id, 'conversation_id=', message.conversation_id, 'sender_id=', message.sender_id, 'seq=', message.seq, 'segments=', message.segments);
// 【重要】ACK消息是发送确认不应该增加未读数
// 在转换为消息格式时添加标记以便MessageManager识别
@@ -813,7 +780,6 @@ private handleNewMetaEvent(message: any): void {
if (message.group_id) {
// 群聊消息确认 - 转换为群聊消息格式
const ackHandlers = this.messageHandlers.get('group_message');
console.log('[WebSocket][DEBUG] 群聊 ack 处理器数量:', ackHandlers?.length || 0);
if (ackHandlers) {
const ackAsGroupMessage: WSGroupChatMessage & { _isAck?: boolean } = {
type: 'group_message',
@@ -826,17 +792,11 @@ private handleNewMetaEvent(message: any): void {
created_at: message.created_at ? new Date(message.created_at).toISOString() : new Date().toISOString(),
_isAck: true, // 标记这是ACK消息
};
console.log('[WebSocket][DEBUG] 转换 ack -> group_message:', {
id: message.id,
sender_id: message.sender_id,
_isAck: true
});
ackHandlers.forEach(handler => handler(ackAsGroupMessage));
}
} else if (message.conversation_id) {
// 私聊消息确认 - 转换为私聊消息格式
const chatHandlers = this.messageHandlers.get('chat');
console.log('[WebSocket][DEBUG] 私聊 ack 处理器数量:', chatHandlers?.length || 0);
if (chatHandlers) {
const ackAsChatMessage: WSChatMessage & { _isAck?: boolean } = {
type: 'chat',
@@ -848,20 +808,13 @@ private handleNewMetaEvent(message: any): void {
created_at: message.created_at ? new Date(message.created_at).toISOString() : new Date().toISOString(),
_isAck: true, // 标记这是ACK消息
};
console.log('[WebSocket][DEBUG] 转换 ack -> chat:', {
id: message.id,
sender_id: message.user_id || message.sender_id,
_isAck: true
});
chatHandlers.forEach(handler => handler(ackAsChatMessage));
}
} else {
console.log('[WebSocket][DEBUG] 跳过 ack 处理: 缺少 group_id 和 conversation_id');
}
break;
default:
console.log('[WebSocket] 未知 meta 详细类型:', detail_type);
}
}
@@ -1059,7 +1012,6 @@ private extractTextFromSegments(segments?: any[]): string {
this.stopReconnect();
this.reconnectTimer = setTimeout(() => {
console.log(`WebSocket 正在重连 (${this.reconnectAttempts + 1}/${this.maxReconnectAttempts})`);
this.reconnectAttempts++;
this.connect();
}, this.reconnectDelay);
@@ -1108,9 +1060,7 @@ private extractTextFromSegments(segments?: any[]): string {
this.lastAppState.match(/inactive|background/) &&
nextAppState === 'active'
) {
console.log('[WebSocket] App 从后台恢复,检查连接状态');
if (!this.isConnected()) {
console.log('[WebSocket] 连接已断开,尝试重连');
// 重置重连计数,允许重新开始重连
this.reconnectAttempts = 0;
this.connect();