diff --git a/internal/heartbeat/reporter.go b/internal/heartbeat/reporter.go index 553b75f..ecedcae 100644 --- a/internal/heartbeat/reporter.go +++ b/internal/heartbeat/reporter.go @@ -18,13 +18,13 @@ import ( // 节点信息存储(通过心跳更新,优先从配置文件读取) var nodeInfo struct { sync.RWMutex - nodeID uint - nodeIP string - country string - province string - city string - isp string - cfg *config.Config + nodeID uint + nodeIP string + country string + province string + city string + isp string + cfg *config.Config initialized bool } @@ -32,7 +32,7 @@ var nodeInfo struct { func InitNodeInfo(cfg *config.Config) { nodeInfo.Lock() defer nodeInfo.Unlock() - + nodeInfo.cfg = cfg nodeInfo.nodeID = cfg.Node.ID nodeInfo.nodeIP = cfg.Node.IP @@ -73,10 +73,10 @@ type Reporter struct { func NewReporter(cfg *config.Config) *Reporter { logger, _ := zap.NewProduction() - + // 初始化节点信息(从配置文件读取) InitNodeInfo(cfg) - + return &Reporter{ cfg: cfg, client: &http.Client{ @@ -123,7 +123,7 @@ func RegisterNode(cfg *config.Config) error { client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Do(req) if err != nil { - return fmt.Errorf("发送心跳失败: %w", err) + return fmt.Errorf("发送心跳失败 (URL: %s): %w", url, err) } defer resp.Body.Close() @@ -173,10 +173,21 @@ func RegisterNode(cfg *config.Config) error { return nil } } - return fmt.Errorf("心跳响应格式无效或节点信息不完整") + return fmt.Errorf("心跳响应格式无效或节点信息不完整 (响应体: %s)", string(body)) } - return fmt.Errorf("心跳请求失败,状态码: %d", resp.StatusCode) + // 读取响应体以便记录错误详情 + body, err := io.ReadAll(resp.Body) + bodyStr := "" + if err == nil && len(body) > 0 { + // 限制响应体长度,避免错误信息过长 + if len(body) > 500 { + bodyStr = string(body[:500]) + "..." + } else { + bodyStr = string(body) + } + } + return fmt.Errorf("心跳请求失败,状态码: %d, URL: %s, 响应体: %s", resp.StatusCode, url, bodyStr) } func (r *Reporter) sendHeartbeat() { @@ -192,7 +203,9 @@ func (r *Reporter) sendHeartbeat() { resp, err := r.client.Do(req) if err != nil { - r.logger.Warn("发送心跳失败", zap.Error(err)) + r.logger.Warn("发送心跳失败", + zap.String("url", url), + zap.Error(err)) return } defer resp.Body.Close() @@ -260,7 +273,21 @@ func (r *Reporter) sendHeartbeat() { } r.logger.Debug("心跳发送成功") } else { - r.logger.Warn("心跳发送失败", zap.Int("status", resp.StatusCode)) + // 读取响应体以便记录错误详情 + body, err := io.ReadAll(resp.Body) + bodyStr := "" + if err == nil && len(body) > 0 { + // 限制响应体长度,避免日志过长 + if len(body) > 500 { + bodyStr = string(body[:500]) + "..." + } else { + bodyStr = string(body) + } + } + + r.logger.Warn("心跳发送失败", + zap.Int("status", resp.StatusCode), + zap.String("url", url), + zap.String("response_body", bodyStr)) } } -