diff --git a/Sources/Nats/NatsConnection.swift b/Sources/Nats/NatsConnection.swift index 5ad73f9..f36fdf1 100644 --- a/Sources/Nats/NatsConnection.swift +++ b/Sources/Nats/NatsConnection.swift @@ -1011,21 +1011,28 @@ class ConnectionHandler: ChannelInboundHandler { oldTask.cancel() } + logger.info("🔄 Starting reconnection process...") + reconnectTask = Task { var connected = false + var attempt = 0 while !Task.isCancelled && (maxReconnects == nil || self.reconnectAttempts < maxReconnects!) { + attempt += 1 + logger.info("🔄 Reconnect attempt \(attempt), total reconnectAttempts: \(self.reconnectAttempts)") do { try await self.connect() connected = true + logger.info("✅ Reconnection successful after \(attempt) attempts") break // Successfully connected } catch is CancellationError { - logger.debug("Reconnect task cancelled") + logger.info("⚠️ Reconnect task cancelled") return } catch { - logger.debug("Could not reconnect: \(error)") + logger.warning("⚠️ Reconnect attempt \(attempt) failed: \(error)") if !Task.isCancelled { + logger.info("⏳ Waiting \(Double(self.reconnectWait) / 1_000_000_000)s before next attempt...") try? await Task.sleep(nanoseconds: self.reconnectWait) } } @@ -1033,13 +1040,13 @@ class ConnectionHandler: ChannelInboundHandler { // Early return if cancelled if Task.isCancelled { - logger.debug("Reconnect task cancelled after connection attempts") + logger.info("⚠️ Reconnect task cancelled after \(attempt) connection attempts") return } // If we got here without connecting and weren't cancelled, we hit max reconnects if !connected { - logger.error("Could not reconnect; maxReconnects exceeded") + logger.error("❌ Could not reconnect; maxReconnects exceeded (\(self.maxReconnects ?? -1))") try? await self.close() return }