diff --git a/src/check_phat_nguoi/__init__.py b/src/check_phat_nguoi/__init__.py index 1406ea7..56175fa 100644 --- a/src/check_phat_nguoi/__init__.py +++ b/src/check_phat_nguoi/__init__.py @@ -1,13 +1,18 @@ import asyncio +from logging import getLogger +from check_phat_nguoi.config.config_reader import config from check_phat_nguoi.get_data import GetData from check_phat_nguoi.notify import SendNotifications from .utils.setup_logger import setup_logger +logger = getLogger(__name__) + async def async_main() -> None: setup_logger() + logger.debug(f"Config read: {config}") await GetData().get_data() await SendNotifications().send() diff --git a/src/check_phat_nguoi/get_data/engines/base.py b/src/check_phat_nguoi/get_data/engines/base.py index 2e25e20..6bd3d50 100644 --- a/src/check_phat_nguoi/get_data/engines/base.py +++ b/src/check_phat_nguoi/get_data/engines/base.py @@ -1,6 +1,7 @@ from __future__ import annotations from abc import abstractmethod +from logging import getLogger from typing import Final, Self from aiohttp import ClientSession @@ -9,18 +10,22 @@ from check_phat_nguoi.config.config_reader import config from check_phat_nguoi.context import PlateInfoModel +logger = getLogger(__name__) + class BaseGetDataEngine: timeout: Final[int] = config.request_timeout def __init__(self) -> None: self.session: ClientSession = ClientSession() + logger.debug(f"Established get data engine session: {type(self).__name__}") async def __aenter__(self) -> Self: return self async def __aexit__(self, exc_type, exc_value, exc_traceback) -> None: await self.session.close() + logger.debug(f"Closed data engine session: {type(self).__name__}") @abstractmethod async def get_data(self, plate: PlateInfoDTO) -> PlateInfoModel | None: ... diff --git a/src/check_phat_nguoi/get_data/engines/check_phat_nguoi.py b/src/check_phat_nguoi/get_data/engines/check_phat_nguoi.py index 4bfa14a..5bc9d21 100644 --- a/src/check_phat_nguoi/get_data/engines/check_phat_nguoi.py +++ b/src/check_phat_nguoi/get_data/engines/check_phat_nguoi.py @@ -34,7 +34,7 @@ class GetDataEngineCheckPhatNguoi(BaseGetDataEngine): headers: Final[dict[str, str]] = {"Content-Type": "application/json"} async def _get_data_request(self, plate: PlateInfoDTO) -> Dict | None: - payload: dict[str, str] = {"bienso": plate.plate} + payload: Final[dict[str, str]] = {"bienso": plate.plate} try: async with self.session.post( API_URL, @@ -50,7 +50,7 @@ async def _get_data_request(self, plate: PlateInfoDTO) -> Dict | None: logger.error( f"Plate {plate.plate}: Time out ({self.timeout}s) getting data from API {API_URL}\n{e}" ) - except ClientError as e: + except (ClientError, Exception) as e: logger.error( f"Plate {plate.plate}: Error occurs while getting data from API {API_URL}\n{e}" ) diff --git a/src/check_phat_nguoi/get_data/get_data.py b/src/check_phat_nguoi/get_data/get_data.py index 511c0ed..90ce272 100644 --- a/src/check_phat_nguoi/get_data/get_data.py +++ b/src/check_phat_nguoi/get_data/get_data.py @@ -36,8 +36,9 @@ async def _get_data_for_plate(self, plate: PlateInfoDTO) -> None: # TODO: @Nguyen thay get_data_engine raise NotImplementedError("csgt.vn has't been implemented yet") case _: # Never reach - logger.error(f"{api}: Not defined!") + logger.error(f"Plate {plate.plate} - {api}: Not defined!") return + logger.info(f"Plate {plate.plate}: Getting data...") plate_info = await get_data_engine.get_data(plate) if plate_info is None: return diff --git a/src/check_phat_nguoi/notify/engines/base.py b/src/check_phat_nguoi/notify/engines/base.py index 8b2647d..235e25e 100644 --- a/src/check_phat_nguoi/notify/engines/base.py +++ b/src/check_phat_nguoi/notify/engines/base.py @@ -1,18 +1,23 @@ +from logging import getLogger from typing import Final, Self from aiohttp import ClientSession from check_phat_nguoi.config.config_reader import config +logger = getLogger(__name__) + class BaseNotificationEngine: timeout: Final[int] = config.request_timeout def __init__(self) -> None: self.session: ClientSession = ClientSession() + logger.debug(f"Established notify engine session: {type(self).__name__}") async def __aenter__(self) -> Self: return self async def __aexit__(self, exc_type, exc_value, exc_traceback) -> None: + logger.debug(f"Closed notify engine session: {type(self).__name__}") await self.session.close() diff --git a/src/check_phat_nguoi/notify/engines/telegram.py b/src/check_phat_nguoi/notify/engines/telegram.py index a5fe840..8e8d899 100644 --- a/src/check_phat_nguoi/notify/engines/telegram.py +++ b/src/check_phat_nguoi/notify/engines/telegram.py @@ -46,17 +46,15 @@ async def _send_message(message: str, plate: str) -> None: logger.error( f"Plate {plate}: Timeout ({self.timeout}s) sending to Telegram Chat ID: {telegram.chat_id}\n{e}" ) - except ClientError as e: + except (ClientError, Exception) as e: logger.error( f"Plate {plate}: Fail to sent to Telegram Chat ID: {telegram.chat_id}\n{e}" ) - except Exception as e: - logger.error(e) - - # TODO: the violation name conventno is not match with param message :v - tasks = ( - _send_message(violation, message.plate) - for message in messages - for violation in message.violations + + await asyncio.gather( + *( + _send_message(violation, message.plate) + for message in messages + for violation in message.violations + ) ) - await asyncio.gather(*tasks) diff --git a/src/check_phat_nguoi/notify/send_notifications.py b/src/check_phat_nguoi/notify/send_notifications.py index 269829d..de49ee8 100644 --- a/src/check_phat_nguoi/notify/send_notifications.py +++ b/src/check_phat_nguoi/notify/send_notifications.py @@ -1,4 +1,5 @@ from asyncio import gather +from logging import getLogger from check_phat_nguoi.config import BaseNotificationDTO, TelegramNotificationDTO from check_phat_nguoi.config.config_reader import config @@ -7,6 +8,8 @@ from .engines.telegram import TelegramNotificationEngine from .markdown_message import MarkdownMessage, MessagesModel +logger = getLogger(__name__) + class SendNotifications: def __init__(self) -> None: @@ -24,7 +27,10 @@ async def send(self) -> None: if notification.enabled ) if not enabled_notifications: + logger.debug(f"Skip notification") return + logger.debug(f"Enabled notification: {enabled_notifications}") + self._md_messages = tuple( MarkdownMessage(plate_info).generate_message() for plate_info in plates_context.plates