66import aiohttp
77import yaml
88from aiohttp import web
9+ from loguru import logger
910
1011
1112class LoadBalancer :
@@ -56,11 +57,11 @@ async def monitor_health(self):
5657 is_healthy = await self .health_check (endpoint )
5758
5859 if not is_healthy and was_healthy :
59- print (f'[Health] Endpoint { endpoint } is down' )
60+ logger . warning (f'Endpoint { endpoint } is down' )
6061 self .unhealthy_endpoints .add (i )
6162 self ._create_weighted_cycles ()
6263 elif is_healthy and not was_healthy :
63- print (f'[Health] Endpoint { endpoint } is back up' )
64+ logger . info (f'Endpoint { endpoint } is back up' )
6465 self .unhealthy_endpoints .remove (i )
6566 self ._create_weighted_cycles ()
6667
@@ -75,7 +76,7 @@ def _create_weighted_cycles(self):
7576 weighted_indices .extend ([i ] * weight )
7677
7778 if not weighted_indices :
78- print ( 'WARNING: All endpoints are unhealthy!' )
79+ logger . critical ( ' All endpoints are unhealthy!' )
7980 weighted_indices = list (range (len (self .endpoints )))
8081
8182 random .shuffle (weighted_indices )
@@ -94,12 +95,12 @@ async def start(self, port: int):
9495 await runner .setup ()
9596 site = web .TCPSite (runner , '0.0.0.0' , port )
9697 await site .start ()
97- print (f'Load balancer running on http://0.0.0.0:{ port } ' )
98+ logger . info (f'Load balancer running on http://0.0.0.0:{ port } ' )
9899
99100 for i , (endpoint , weight ) in enumerate (
100101 zip (self .endpoints , self .weights )
101102 ):
102- print (f'Endpoint { i } : { endpoint } (weight: { weight } )' )
103+ logger . info (f'Endpoint { i } : { endpoint } (weight: { weight } )' )
103104
104105 async def handle_request (self , request : web .Request ) -> web .StreamResponse :
105106 cors_headers = {
@@ -126,6 +127,10 @@ async def handle_request(self, request: web.Request) -> web.StreamResponse:
126127 if request .query_string :
127128 path += f'?{ request .query_string } '
128129 target_url = f"{ target_url .rstrip ('/' )} /{ path .lstrip ('/' )} "
130+
131+ logger .info (
132+ f"Routing { request .method } { path } to endpoint "
133+ f"{ endpoint_index } : { target_url } " )
129134
130135 try :
131136 assert self .client_session is not None
@@ -149,7 +154,7 @@ async def handle_request(self, request: web.Request) -> web.StreamResponse:
149154 return response
150155
151156 except Exception as e :
152- print (f'Request failed: { str (e )} ' )
157+ logger . error (f'Request failed: { str (e )} ' )
153158 raise
154159
155160 async def cleanup (self ):
0 commit comments