diff --git a/mem_checker/mem_checker.py b/mem_checker/mem_checker.py index 371d1b6..17a6c6a 100644 --- a/mem_checker/mem_checker.py +++ b/mem_checker/mem_checker.py @@ -18,7 +18,9 @@ The request contains the following json format: """ import json +import logging import subprocess +import sys import urllib.parse import urllib.request from abc import ABC, abstractmethod @@ -28,10 +30,21 @@ from time import sleep ENDPOINT_URL = "http://127.0.0.1:8000/user" # endpoint for send alerts FREE_IN_MB = 500 # free: the value of the trigger in megabytes FREE_IN_GB = 0.5 # free: the value of the trigger in gigabytes -DF_IN_PERCENT = 90 # df: the value of the trigger in percents +DF_IN_PERCENT = 50 # df: the value of the trigger in percents SLEEPTIME = 5 # main_loop sleep time per seconds +logger = logging.getLogger("mem_checker_logger") +logger.setLevel(logging.DEBUG) +console_handler = logging.StreamHandler() +console_handler.setLevel(logging.DEBUG) +formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") +console_handler.setFormatter(formatter) + +# Добавляем обработчик в логгер +logger.addHandler(console_handler) + + @dataclass() class MessageDTO: type_msg: str @@ -108,6 +121,7 @@ class FreeMem(Command): memory = memory[:-2].replace(",", ".") memory_value = float(memory) if "." in memory else int(memory) except Exception as e: + logger.error(e) return [ MessageDTO( type_msg="ParserError", @@ -157,25 +171,28 @@ def send_alert(alerts: list[MessageDTO]) -> None: headers={"Content-Type": "application/json"}, method="POST", ) - with urllib.request.urlopen(req) as response: - response.read().decode("utf-8") + try: + with urllib.request.urlopen(req) as response: + response.read().decode("utf-8") + except Exception as e: + logger.error(e) def main_loop() -> None: free_mem = FreeMem() hdd_mem = FreeHdd() - while True: - alerts: list[MessageDTO] = list() + alerts: list[MessageDTO] = list() - alerts.extend(free_mem.get_alerts()) - alerts.extend(hdd_mem.get_alerts()) + alerts.extend(free_mem.get_alerts()) + alerts.extend(hdd_mem.get_alerts()) - if alerts: - send_alert(alerts=alerts) - - sleep(SLEEPTIME) + if alerts: + send_alert(alerts=alerts) if __name__ == "__main__": - main_loop() + if "--test-mode" in sys.argv: + while True: + main_loop() + sleep(SLEEPTIME)