From 9ecb29225a881bbc09945e3034edd6c05b6d5461 Mon Sep 17 00:00:00 2001 From: lafay <2021211506@stu.hit.edu.cn> Date: Thu, 26 Mar 2026 22:04:37 +0800 Subject: [PATCH] feat(ws_handler): enhance WebSocket logging for connection events - Added logging for WebSocket connection attempts, client connections, disconnections, and message receptions to improve traceability and debugging. - Implemented detailed logs in readPump to capture user and client IDs during various WebSocket events, enhancing visibility into client interactions. --- internal/handler/ws_handler.go | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/internal/handler/ws_handler.go b/internal/handler/ws_handler.go index 4857724..7b760a0 100644 --- a/internal/handler/ws_handler.go +++ b/internal/handler/ws_handler.go @@ -81,6 +81,9 @@ func (h *WSHandler) HandleWebSocket(c *gin.Context) { } userID := claims.UserID + zap.L().Info("WebSocket connection attempt", + zap.String("user_id", userID), + ) // 2. 升级HTTP连接为WebSocket conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) @@ -105,6 +108,11 @@ func (h *WSHandler) HandleWebSocket(c *gin.Context) { replayEvents := h.wsHub.Register(client) defer h.wsHub.Unregister(client) + zap.L().Info("WebSocket client connected", + zap.String("user_id", userID), + zap.Uint64("client_id", clientID), + ) + // 5. 发送历史回放消息 go func() { for _, ev := range replayEvents { @@ -126,21 +134,38 @@ func (h *WSHandler) HandleWebSocket(c *gin.Context) { // 6. 启动读写goroutine go h.writePump(conn, client) h.readPump(conn, client) + + zap.L().Info("WebSocket client disconnected", + zap.String("user_id", userID), + zap.Uint64("client_id", clientID), + ) } // readPump 读取客户端消息 func (h *WSHandler) readPump(conn *websocket.Conn, client *ws.Client) { defer func() { + zap.L().Info("WebSocket readPump exiting", + zap.String("user_id", client.UserID), + zap.Uint64("client_id", client.ID), + ) conn.Close() }() conn.SetReadLimit(64 * 1024) // 64KB conn.SetReadDeadline(time.Now().Add(60 * time.Second)) conn.SetPongHandler(func(string) error { + zap.L().Debug("WebSocket pong received", + zap.String("user_id", client.UserID), + ) conn.SetReadDeadline(time.Now().Add(60 * time.Second)) return nil }) + zap.L().Info("WebSocket readPump started", + zap.String("user_id", client.UserID), + zap.Uint64("client_id", client.ID), + ) + for { _, message, err := conn.ReadMessage() if err != nil { @@ -149,6 +174,11 @@ func (h *WSHandler) readPump(conn *websocket.Conn, client *ws.Client) { zap.String("user_id", client.UserID), zap.Error(err), ) + } else { + zap.L().Info("WebSocket connection closed", + zap.String("user_id", client.UserID), + zap.Error(err), + ) } break } @@ -160,6 +190,11 @@ func (h *WSHandler) readPump(conn *websocket.Conn, client *ws.Client) { continue } + zap.L().Debug("WebSocket message received", + zap.String("user_id", client.UserID), + zap.String("type", msg.Type), + ) + // 处理消息 h.handleMessage(client, &msg) }