Skip to content
This repository has been archived by the owner on Jan 18, 2025. It is now read-only.

Commit

Permalink
chore: add more log info
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinNitroG committed Jan 8, 2025
1 parent 0b39bec commit 4f05f68
Show file tree
Hide file tree
Showing 7 changed files with 33 additions and 13 deletions.
5 changes: 5 additions & 0 deletions src/check_phat_nguoi/__init__.py
Original file line number Diff line number Diff line change
@@ -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()

Expand Down
5 changes: 5 additions & 0 deletions src/check_phat_nguoi/get_data/engines/base.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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: ...
4 changes: 2 additions & 2 deletions src/check_phat_nguoi/get_data/engines/check_phat_nguoi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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}"
)
Expand Down
3 changes: 2 additions & 1 deletion src/check_phat_nguoi/get_data/get_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions src/check_phat_nguoi/notify/engines/base.py
Original file line number Diff line number Diff line change
@@ -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()
18 changes: 8 additions & 10 deletions src/check_phat_nguoi/notify/engines/telegram.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
6 changes: 6 additions & 0 deletions src/check_phat_nguoi/notify/send_notifications.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -7,6 +8,8 @@
from .engines.telegram import TelegramNotificationEngine
from .markdown_message import MarkdownMessage, MessagesModel

logger = getLogger(__name__)


class SendNotifications:
def __init__(self) -> None:
Expand All @@ -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
Expand Down

0 comments on commit 4f05f68

Please sign in to comment.