Skip to content

Commit e8f5fa0

Browse files
committed
add logging
1 parent 0fd5b0a commit e8f5fa0

File tree

3 files changed

+23
-8
lines changed

3 files changed

+23
-8
lines changed

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ requires-python = ">=3.8"
1010
dependencies = [
1111
"aiohttp>=3.8.0",
1212
"pyyaml>=6.0",
13+
"loguru>=0.7.0",
1314
]
1415

1516
[project.optional-dependencies]

src/aphrodite_loadbalancer/__main__.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
import asyncio
22
import sys
33

4+
from loguru import logger
5+
46
from .loadbalancer import LoadBalancer
57

68

9+
logger.remove()
10+
logger.add(
11+
sys.stderr,
12+
format="<green>{time:HH:mm:ss}</green> | <level>{message}</level>",
13+
)
14+
15+
716
def main():
817
if len(sys.argv) != 2:
9-
print('Usage: aphrodite-loadbalancer <config.yaml>')
18+
logger.error('Usage: aphrodite-loadbalancer <config.yaml>')
1019
sys.exit(1)
1120

1221
config_path = sys.argv[1]
@@ -21,7 +30,7 @@ async def async_main(config_path: str):
2130
while True:
2231
await asyncio.sleep(3600)
2332
except KeyboardInterrupt:
24-
print('\nShutting down...')
33+
logger.info('\nShutting down...')
2534
finally:
2635
await balancer.cleanup()
2736

src/aphrodite_loadbalancer/loadbalancer.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import aiohttp
77
import yaml
88
from aiohttp import web
9+
from loguru import logger
910

1011

1112
class 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

Comments
 (0)