Skip to content

Commit 9b2955d

Browse files
authored
Logging (#18)
* add loguru as dependency * replace print statements with logging statements
1 parent 4b3e470 commit 9b2955d

File tree

4 files changed

+60
-29
lines changed

4 files changed

+60
-29
lines changed

pyproject.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ classifiers = [
6161
]
6262

6363
requires-python = ">=3.10"
64-
dependencies = []
64+
dependencies = [
65+
"loguru>=0.7.3",
66+
]
6567

6668
[build-system]
6769
requires = ["uv_build>=0.7.19,<0.8"]

src/chordnet/net.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import threading
55
from typing import Callable, Tuple
66

7+
from loguru import logger as log
8+
79
from .address import Address
810

911
callback = Callable[[str, list[str]], str| Address | None]
@@ -86,7 +88,7 @@ def send_request(
8688
request_args = ':'.join(str(arg) for arg in args)
8789
request = f"{method}:{request_args}"
8890
if (method == "TRACE_SUCCESSOR"):
89-
print ('[SENDING TRACE REQ]', request)
91+
log.debug("[SENDING TRACE REQ]", request)
9092
# Send the request
9193
sock.send(request.encode())
9294

@@ -96,13 +98,13 @@ def send_request(
9698
return response
9799

98100
except socket.timeout:
99-
print("Request timed out", file=sys.stderr)
101+
log.info("Request timed out")
100102
return None
101103
except ConnectionRefusedError:
102-
print("Connection refused", file=sys.stderr)
104+
log.info("Connection refused")
103105
return None
104106
except Exception as e:
105-
print(f"Network request error: {e}", file=sys.stderr)
107+
log.info(f"Network request error: {e}")
106108
return None
107109

108110

@@ -129,7 +131,7 @@ def _listen_for_connections(self) -> None:
129131
).start()
130132
except Exception as e:
131133
if self._running:
132-
print(f"Error accepting connection: {e}\n")
134+
log.info(f"Error accepting connection: {e}\n")
133135
sys.stderr.write(f"Error accepting connection: {e}\n")
134136
sys.stderr.flush()
135137

@@ -149,13 +151,13 @@ def _handle_connection(self, client_socket: socket.socket) -> None:
149151
method, *args = request.split(':')
150152

151153
if method == 'TRACE_SUCCESSOR':
152-
print(f"[NET]Received request: {request}", file=sys.stderr)
154+
log.debug(f"[NET]Received request: {request}")
153155

154156
# Dispatch to appropriate method
155157
response = self._request_handler(method, args)
156158

157159
if method == 'TRACE_SUCCESSOR':
158-
print(f"[NET]Sent response: {response}", file=sys.stderr)
160+
log.debug(f"[NET]Sent response: {response}")
159161

160162
# Send response
161163
client_socket.send(str(response).encode())

src/chordnet/node.py

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
"""node.py: Represents a node on a ring."""
2-
import sys
32
from typing import Callable, Tuple
43

4+
from loguru import logger as log
5+
56
from .address import Address
67
from .net import _Net
78

@@ -95,7 +96,7 @@ def join(self, known_ip: str, known_port: int) -> None:
9596
self.finger_table[0] = self._parse_address(response)
9697
msg = f"Node {self.address.key} joined the ring. " \
9798
"Successor: {self.successor().key}"
98-
print(msg, file=sys.stderr)
99+
log.info(msg)
99100
else:
100101
raise ValueError("Failed to find successor. Join failed")
101102

@@ -104,7 +105,7 @@ def join(self, known_ip: str, known_port: int) -> None:
104105

105106

106107
except Exception as e:
107-
print(f"Join failed: {e}")
108+
log.info(f"Join failed: {e}")
108109
raise
109110

110111

@@ -118,15 +119,15 @@ def fix_fingers(self) -> None:
118119
gap = (2 ** self._next) % (2 ** Address._M)
119120

120121
start = self.address.key + gap
121-
#print(f"fixing finger {self._next}. gap is {gap}, " \
122+
#log.info(f"fixing finger {self._next}. gap is {gap}, " \
122123
#"start of interval is: {start}")
123124

124125
try:
125126
# Find the successor for this finger's start position
126127
responsible_node = self.find_successor(start)
127128
self.finger_table[self._next] = responsible_node
128129
except Exception as e:
129-
print(f"fix_fingers failed for finger {self._next}: {e}")
130+
log.debug(f"fix_fingers failed for finger {self._next}: {e}")
130131

131132
# Move to the next finger table entry, wrapping around if necessary
132133
self._next = (self._next + 1) % Address._M
@@ -153,7 +154,7 @@ def start_periodic_tasks(self, interval=1.0):
153154
"""
154155
if self._fix_fingers_timer and self._fix_fingers_timer.is_alive():
155156
# Timer is already running, no need to start again
156-
print("Periodic tasks are already running.", file=sys.stderr)
157+
log.info("Periodic tasks are already running.")
157158
return
158159
self.is_running = True
159160
self._run_fix_fingers(interval)
@@ -173,7 +174,7 @@ def log_finger_table(self) -> None:
173174
for i, finger in enumerate(self.finger_table):
174175
message += f" Finger[{i}] -> {finger}\n"
175176

176-
print(message, file=sys.stderr)
177+
log.info(message)
177178

178179
def find_successor(self, id: int) -> Address:
179180
"""Finds the successor node for a given identifier.
@@ -210,7 +211,7 @@ def find_successor(self, id: int) -> Address:
210211
return successor if successor else self.address
211212

212213
except Exception as e:
213-
print(f"Find successor failed: {e}")
214+
log.info(f"Find successor failed: {e}")
214215
# Fallback to local successor if network request fails
215216
return curr_successor if curr_successor else self.address
216217

@@ -278,31 +279,31 @@ def stabilize(self) -> None:
278279

279280
try:
280281
# Get the predecessor of the current successor
281-
#print(f"stabilize: checking successor {self.successor().key}" \
282-
#for predecessor", file=sys.stderr)
282+
#log.info(f"stabilize: checking successor {self.successor().key}" \
283+
#for predecessor")
283284
x_response = self._net.send_request(
284285
curr_successor, 'GET_PREDECESSOR')
285286

286-
#print(f"stabilize: predecessor found: {x_response}",
287+
#log.info(f"stabilize: predecessor found: {x_response}",
287288
#file=sys.stderr)
288289
x = self._parse_address(x_response)
289290

290291
if x and self._is_between(
291292
self.address.key, curr_successor.key, x.key
292293
):
293294
self.finger_table[0] = x
294-
#print(
295+
#log.info(
295296
#f"stabilize: updated successor to {self.successor().key}",
296297
#file=sys.stderr)
297298
# otherwise, we just notify them that we exist.
298299
# This is usually for the first joiner to a ring.
299300

300-
#print(f"Node {self.address} - Updated Successor:" \
301+
#log.info(f"Node {self.address} - Updated Successor:" \
301302
#"{self.successor()}, Predecessor: {self.predecessor}",
302303
#file=sys.stderr)
303304

304305
except Exception as e:
305-
print(f"Stabilize failed: {e}", file=sys.stderr)
306+
log.info(f"Stabilize failed: {e}")
306307
finally:
307308
self.notify(self.successor())
308309

@@ -332,7 +333,7 @@ def notify(self, potential_successor: Address | None)-> bool:
332333
else:
333334
return False
334335
except Exception as e:
335-
print(f"Notify failed: {e}", file=sys.stderr)
336+
log.info(f"Notify failed: {e}")
336337
return False
337338

338339

@@ -449,7 +450,7 @@ def trace_successor(
449450
id,
450451
curr_hops
451452
)
452-
print(f"Raw response: {response}", file=sys.stderr) # Debugging line
453+
log.debug(f"Raw response: {response}") # Debugging line
453454
assert response is not None
454455
parts = response.split(":")
455456
if len(parts) != 4:
@@ -459,14 +460,14 @@ def trace_successor(
459460
# resolved_node.key = int(node_key)
460461
response_split = response.split(":")
461462
address = ':'.join(response_split[:-1])
462-
print ("[trace]Joined Address :", address)
463+
log.info("[trace]Joined Address :", address)
463464
# address = '':'.join(response[:2])
464465
return address, int(hops)+1
465466

466467
# return self._parse_address(response), hops
467468

468469
except Exception as e:
469-
print(f"trace successor failed: {e}")
470+
log.info(f"trace successor failed: {e}")
470471
# Fallback to local successor if network request fails
471472
return str(self.successor()), -1
472473

@@ -490,14 +491,14 @@ def _process_request(
490491
elif method == "TRACE_SUCCESSOR":
491492
try:
492493
id, hops = int(args[0]), int(args[1])
493-
print ("[NODE] Current ID ", id, "Current hops ", hops)
494+
log.info("[NODE] Current ID ", id, "Current hops ", hops)
494495
successor, hops = self.trace_successor(id, hops)
495496

496-
print ("SUCCESSSOR NODE :", successor, "HOPS :", hops)
497+
log.info("SUCCESSSOR NODE :", successor, "HOPS :", hops)
497498
returnString = f"{successor}:{hops}"
498499
return returnString
499500
except Exception as e:
500-
print(f"TRACE_SUCCESSOR error: {e}", file=sys.stderr)
501+
log.info(f"TRACE_SUCCESSOR error: {e}")
501502
return "ERROR:Invalid TRACE_SUCCESSOR Request"
502503

503504
elif method == 'GET_PREDECESSOR':

uv.lock

Lines changed: 26 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)