각 메서드 로그개선

This commit is contained in:
2023-04-30 10:26:08 +09:00
parent 17757e883e
commit 80688a3187
2 changed files with 53 additions and 40 deletions

View File

@ -87,10 +87,10 @@ class DaminationAPI():
if widgets[0]: if widgets[0]:
for widget in widgets: for widget in widgets:
await self.add_widget_and_start_fetching_notifications(widget) await self.add_widget_and_start_fetching_notifications(widget)
logger.info(f"initialize wigets : {widgets}") logger.info(f"[initialize_widgets] WIDGET ID 초기화 : {widgets}")
else: else:
logger.error(f"widgets empty") logger.error(f"[initialize_widgets] WIDGET 초기화 실패 - 등록된 WIDGET ID 없음")
async def process_notification(self): async def process_notification(self):
@ -99,9 +99,9 @@ class DaminationAPI():
if donate is not None: if donate is not None:
for widget_id, value in donate.items(): for widget_id, value in donate.items():
await self.send_notifications_to_subscribers(widget_id, value) await self.send_notifications_to_subscribers(widget_id, value)
logger.debug(f"[process_notification] QUEUE 추출: {widget_id, value}")
else: else:
logger.error("No notifications in the queue, breaking loop.") logger.error("[process_notification] QUEUE 추출 실패 - 저장된 QUEUE 없음")
break break
@ -113,11 +113,11 @@ class DaminationAPI():
if widget_id in self.subscribers: if widget_id in self.subscribers:
subscribers = self.subscribers[widget_id] subscribers = self.subscribers[widget_id]
logger.info(f"get {widget_id} subscribers : {subscribers}") logger.info(f"[get_subscribers] 구독자 반환({widget_id}) : {subscribers}")
return subscribers return subscribers
else: else:
logger.error(f"no subscribers") logger.error(f"[get_subscribers] 구독자 없음({widget_id})")
return [] return []
@ -127,22 +127,22 @@ class DaminationAPI():
if url not in self.subscribers[widget_id]: if url not in self.subscribers[widget_id]:
self.subscribers[widget_id].append(url) self.subscribers[widget_id].append(url)
logger.info(f"Added subscriber: widget_id={widget_id}, url={url}") logger.info(f"[add_subscriber] 구독자 추가 widget_id={widget_id}, url={url}")
return widget_id return widget_id
else: else:
logger.error(f"Subscriber already exists: widget_id={widget_id}, url={url}") logger.error(f"[add_subscriber] 이미 추가된 구독자 widget_id={widget_id}, url={url}")
return '' return ''
def remove_subscriber(self, widget_id: str, url: str) -> str: def remove_subscriber(self, widget_id: str, url: str) -> str:
if widget_id in self.subscribers and url in self.subscribers[widget_id]: if widget_id in self.subscribers and url in self.subscribers[widget_id]:
self.subscribers[widget_id].remove(url) self.subscribers[widget_id].remove(url)
logger.info(f"Removed subscriber: widget_id={widget_id}, url={url}") logger.info(f"[remove_subscriber] 구독자 제거: widget_id={widget_id}, url={url}")
return widget_id return widget_id
else: else:
logger.error(f"Subscriber not found: widget_id={widget_id}, url={url}") logger.error(f"[remove_subscriber] 구독자를 찾을 수 없음 widget_id={widget_id}, url={url}")
return '' return ''
@ -151,11 +151,11 @@ class DaminationAPI():
현재 설정된 모든 위젯 ID 목록을 반환합니다. 현재 설정된 모든 위젯 ID 목록을 반환합니다.
""" """
if self.WIDGET_IDS: if self.WIDGET_IDS:
logger.info(f"get widget {self.WIDGET_IDS}") logger.info(f"[get_widget_ids] WIDGET ID 반환 {self.WIDGET_IDS}")
return self.WIDGET_IDS return self.WIDGET_IDS
else: else:
logger.error(f"widget id empty") logger.error(f"[get_widget_ids] WIDGET ID 반환 실패 - WIDGET ID 없음")
return [] return []
@ -167,11 +167,11 @@ class DaminationAPI():
try: try:
if widget_id not in self.WIDGET_IDS: if widget_id not in self.WIDGET_IDS:
self.WIDGET_IDS.append(widget_id) self.WIDGET_IDS.append(widget_id)
logger.info(f"add widget {widget_id}") logger.info(f"[add_widget_id] WIDGET ID 추가 {widget_id}")
return widget_id return widget_id
else: else:
logger.error(f"{widget_id} already exists in the list.") logger.error(f"[add_widget_id] 이미 추가된 WIDGET ID {widget_id}")
return '' return ''
except Exception as e: except Exception as e:
@ -188,11 +188,11 @@ class DaminationAPI():
try: try:
if widget_id in self.WIDGET_IDS: if widget_id in self.WIDGET_IDS:
widget = self.WIDGET_IDS.pop(self.WIDGET_IDS.index(widget_id)) widget = self.WIDGET_IDS.pop(self.WIDGET_IDS.index(widget_id))
logger.info(f"remove widget {widget}") logger.info(f"[remove_widget_id] WIDGET ID 제거 {widget}")
return widget return widget
else: else:
logger.error(f"not in widget") logger.error(f"[remove_widget_id] WIDGET ID 제거 실패 - WIDGET ID를 찾을 수 없음")
return '' return ''
except Exception as e: except Exception as e:
@ -218,7 +218,7 @@ class DaminationAPI():
async with connect(wss_url, ping_interval=12) as websocket: async with connect(wss_url, ping_interval=12) as websocket:
token = json.loads(await websocket.recv())['token'] token = json.loads(await websocket.recv())['token']
logger.debug(f"token : {token}") logger.debug(f"token : {token}")
logger.info(f"WebSocket connection established for widget_id: {widget_id}") logger.info(f"[fetch_notifications] 웹 소켓 연결 : {widget_id}")
while True: while True:
message = await websocket.recv() message = await websocket.recv()
@ -229,23 +229,24 @@ class DaminationAPI():
reformed_data = Donate(**alert_data) reformed_data = Donate(**alert_data)
except Exception as e: except Exception as e:
logger.error(f"Error: {e}, Raw data: {alert_data}") logger.error(f"[fetch_notifications] Error: {e}, Raw data: {alert_data}")
pass pass
await queue.put({widget_id: json.loads(reformed_data.json().encode('utf-8').decode('unicode_escape'))}) await queue.put({widget_id: json.loads(reformed_data.json().encode('utf-8').decode('unicode_escape'))})
except asyncio.CancelledError: except asyncio.CancelledError:
logger.info(f"Widget {widget_id} fetching task was cancelled.") logger.info(f"[fetch_notifications] 웹 소켓 연결 취소 : {widget_id}")
break break
except Exception as e: except Exception as e:
logger.error(f"Error: {e}")
retries += 1 retries += 1
logger.error(f"[fetch_notifications] 웹 소켓 연결 실패 : {e}, 재시도 : {retries}")
await asyncio.sleep(2 ** retries) await asyncio.sleep(2 ** retries)
if retries > 2:
self.remove_widget_id(widget_id) self.remove_widget_id(widget_id)
logger.info(f"Connection failed for widget_id: {widget_id}") logger.info(f"[fetch_notifications] 연결 실패 : {widget_id}")
@staticmethod @staticmethod
@ -274,10 +275,11 @@ class DaminationAPI():
self.add_widget_id(widget_id) self.add_widget_id(widget_id)
task = asyncio.create_task(self.fetch_notifications(self.queue, widget_id)) task = asyncio.create_task(self.fetch_notifications(self.queue, widget_id))
self.fetch_tasks.append(task) self.fetch_tasks.append(task)
logger.info(f"[add_widget_and_start_fetching_notifications] 투네이션 알림 수신 시작 : {widget_id}")
return widget_id return widget_id
else: else:
logger.error(f"Widget ID {widget_id} already exists in the list.") logger.error(f"[add_widget_and_start_fetching_notifications] 이미 투네이션 알림 수신 중 : {widget_id}")
return '' return ''
@ -292,13 +294,14 @@ class DaminationAPI():
fetch_task = self.fetch_tasks.pop(index) fetch_task = self.fetch_tasks.pop(index)
fetch_task.cancel() fetch_task.cancel()
await fetch_task await fetch_task
logger.info(f"[remove_widget_and_stop_fetching_notifications] 투네이션 알림 수신 중단 : {widget_id}")
return widget_id return widget_id
else: else:
logger.error(f"Widget ID {widget_id} not found.") logger.error(f"[remove_widget_and_stop_fetching_notifications] 수신중인 투네이션 알림을 찾을 수 없음 {widget_id}")
return '' return ''
async def pop_notification_from_queue(self): async def pop_notification_from_queue(self) -> dict:
""" """
queue에서 가장 먼저 저장된 항목을 꺼내어 반환합니다. queue에서 가장 먼저 저장된 항목을 꺼내어 반환합니다.
queue가 비어있는 경우 None을 반환합니다. queue가 비어있는 경우 None을 반환합니다.
@ -307,7 +310,7 @@ class DaminationAPI():
item = await self.queue.get() item = await self.queue.get()
return item return item
else: else:
return None return {}
async def get_connection(self, url: str): async def get_connection(self, url: str):
@ -335,9 +338,9 @@ class DaminationAPI():
async with session.post(subscriber_url, json=payload) as response: async with session.post(subscriber_url, json=payload) as response:
if response.status == 200: if response.status == 200:
logger.info(f"Successfully sent Webhook to {subscriber_url}, {payload}") logger.info(f"[send_notification_webhook] 알림 전송 {subscriber_url}, {payload}")
else: else:
logger.error(f"Failed to send notification to {subscriber_url} with status code {response.status}.") logger.error(f"[send_notification_webhook] 알림 전송 실패 {subscriber_url}, 응답: {response.status}")
async def run(self): async def run(self):

View File

@ -10,6 +10,10 @@ app = web.Application()
@routes.get('/get_subscriber/{widget_id}') @routes.get('/get_subscriber/{widget_id}')
async def get_widgets(request): async def get_widgets(request):
"""
주어진 widget_id로 연결된 구독 목록을 반환합니다.
사용 예: http://localhost/get_subscriber?widget_id=YOUR_WIDGET_ID
"""
widget_id = request.match_info['widget_id'] widget_id = request.match_info['widget_id']
subscribers = toonat.get_subscribers(widget_id) subscribers = toonat.get_subscribers(widget_id)
if subscribers: if subscribers:
@ -22,36 +26,39 @@ async def get_widgets(request):
async def subscribe(request): async def subscribe(request):
""" """
주어진 widget_id와 url로 구독을 추가합니다. 주어진 widget_id와 url로 구독을 추가합니다.
사용 예: http://localhost/subscribe/YOUR_WIDGET_ID?url=YOUR_WEBHOOK_URL
""" """
widget_id = request.match_info['widget_id'] widget_id = request.match_info['widget_id']
url = request.query['url'] url = request.query['url']
success = toonat.add_subscriber(widget_id, url) success = toonat.add_subscriber(widget_id, url)
if success: if success:
return web.Response(text=f"Subscribed to widget ID {success} with URL {url}.") return web.Response(text=f"Subscribed to widget ID {success} with URL {url}")
else: else:
return web.Response(text=f"Already subscribed to widget ID {widget_id} with URL {url}.") return web.Response(text=f"Already subscribed to widget ID {widget_id} with URL {url}")
@routes.get('/unsubscribe/{widget_id}') @routes.get('/unsubscribe/{widget_id}')
async def unsubscribe(request): async def unsubscribe(request):
""" """
주어진 widget_id와 url로 구독을 취소합니다. 주어진 widget_id와 url로 구독을 취소합니다.
사용 예: http://localhost/unusbscribe/YOUR_WIDGET_ID?=url=YOUR_WEBHOOK_URL
""" """
widget_id = request.match_info['widget_id'] widget_id = request.match_info['widget_id']
url = request.query['url'] url = request.query['url']
success = toonat.remove_subscriber(widget_id, url) success = toonat.remove_subscriber(widget_id, url)
if success: if success:
return web.Response(text=f"Unsubscribed from widget ID {success} with URL {url}.") return web.Response(text=f"Unsubscribed from widget ID {success} with URL {url}")
else: else:
return web.Response(text=f"Not subscribed to widget ID {widget_id} with URL {url}.") return web.Response(text=f"Not subscribed to widget ID {widget_id} with URL {url}")
@routes.get('/get_widgets') @routes.get('/get_widgets')
async def get_widgets(request): async def get_widgets(request):
""" """
현재 설정된 모든 위젯 ID 목록을 반환하는 웹 API 엔드포인트입니다. 현재 설정된 모든 위젯 ID 목록을 반환니다.
사용 예: http://localhost/get_widgets
""" """
widget_ids = toonat.get_widget_ids() widget_ids = toonat.get_widget_ids()
@ -64,29 +71,31 @@ async def get_widgets(request):
@routes.get('/add_widget') @routes.get('/add_widget')
async def add_widget(request): async def add_widget(request):
""" """
주어진 widget_id를 위젯 ID 목록에 추가하고 알림을 가져오는 작업을 시작하는 웹 API 엔드포인트입니다. 주어진 widget_id를 위젯 ID 목록에 추가하고 알림을 가져오는 작업을 시작니다.
widget_id: 추가할 위젯 ID widget_id: 추가할 위젯 ID
사용 예: http://localhost/add_widget?=widget_id=YOUR_WIDGET_ID
""" """
widget_id = request.query['widget_id'] widget_id = request.query['widget_id']
success = await toonat.add_widget_and_start_fetching_notifications(widget_id) success = await toonat.add_widget_and_start_fetching_notifications(widget_id)
if success: if success:
return web.Response(text=f"Widget ID {success} added and fetching started.") return web.Response(text=f"Widget ID {success} added and fetching started")
else: else:
return web.Response(text=f"no widget_ids") return web.Response(text=f"Already {widget_id} in the list")
@routes.get('/remove_widget') @routes.get('/remove_widget')
async def remove_widget(request): async def remove_widget(request):
""" """
주어진 widget_id를 위젯 ID 목록에서 제거하고 알림을 가져오는 작업을 중단하는 웹 API 엔드포인트입니다. 주어진 widget_id를 위젯 ID 목록에서 제거하고 알림을 가져오는 작업을 중단니다.
widget_id: 제거할 위젯 ID widget_id: 제거할 위젯 ID
사용 예: http://localhost/remove_widget?=YOUR_WIDGET_ID
""" """
widget_id = request.query['widget_id'] widget_id = request.query['widget_id']
success = await toonat.remove_widget_and_stop_fetching_notifications(widget_id) success = await toonat.remove_widget_and_stop_fetching_notifications(widget_id)
if success: if success:
return web.Response(text=f"Widget ID {success} removed and fetching stopped.") return web.Response(text=f"Widget ID {success} removed and fetching stopped")
else: else:
return web.Response(text=f"Not in widget list {widget_id}") return web.Response(text=f"Not in widget list {widget_id}")
@ -95,6 +104,7 @@ async def remove_widget(request):
async def status(request): async def status(request):
""" """
서버 상태를 확인하는 웹 API 엔드포인트입니다. 이 엔드포인트는 서버가 정상적으로 작동 중임을 확인하는 데 사용됩니다. 서버 상태를 확인하는 웹 API 엔드포인트입니다. 이 엔드포인트는 서버가 정상적으로 작동 중임을 확인하는 데 사용됩니다.
DOCKER Health Check에 사용됩니다.
""" """
return web.HTTPOk() return web.HTTPOk()
@ -124,7 +134,7 @@ async def main():
if __name__ == "__main__": if __name__ == "__main__":
if not toonat.WIDGET_IDS: if not toonat.WIDGET_IDS:
print("No widget ID found in settings.ini.") print("settings.ini 파일에서 위젯 ID를 찾을 수 없습니다")
print("Please enter the widget ID via web endpoint (http://localhost/add_widget/YOUR_WIDGET_ID)") print("웹 엔드포인트(http://localhost/add_widget/YOUR_WIDGET_ID)를 통해 위젯 ID를 입력해주세요")
asyncio.run(main()) asyncio.run(main())