소스 검색

improve script logging

Clovis JAQUIN 2 년 전
부모
커밋
c4be0c048c
3개의 변경된 파일33개의 추가작업 그리고 5개의 파일을 삭제
  1. 13 2
      script/KdeConnect.py
  2. 2 0
      script/run.sh
  3. 18 3
      script/send_sms.py

+ 13 - 2
script/KdeConnect.py

@@ -1,4 +1,5 @@
 import subprocess
+import logging
 import re
 
 from pydantic import BaseModel
@@ -64,9 +65,17 @@ class KDEConnect:
         command: list[str] = ["kdeconnect-cli"]
         command.extend(args)
         process: CompletedProcess = subprocess.run(command, capture_output=True)
+
+        subprocess_response = process.stdout.decode("utf-8")
+        logging.debug("Subprocess call : \n>> " + " ".join(command) + "\n" + subprocess_response)
         if process.stderr != b"":
-            print(f"[Err] {process.stderr.decode('utf-8')}")
-        return process.stdout.decode("utf-8")
+            error_msg: str = process.stderr.decode("utf-8")
+            if error_msg.endswith("devices found\n"):
+                logging.info(error_msg)
+            else:
+                raise KDEConnectError(error_msg)
+
+        return subprocess_response
 
     @staticmethod
     def get_device_list() -> list[KDEDevice]:
@@ -75,6 +84,8 @@ class KDEConnect:
         output: list[KDEDevice] = []
         device_entries: list[str] = KDEConnect.run_kde_command(["-l"]).strip().split("\n")
         for device_str in device_entries:
+            if device_str == "":
+                continue
             result = re.search("^- ([^:]+): ([a-z0-9_]{36})", device_str)
             reachable = "reachable" in device_str
             paired = "paired" in device_str

+ 2 - 0
script/run.sh

@@ -1,5 +1,7 @@
 #!/usr/bin/env bash
 
+cd /home/clovis/Documents/bdlg2023-sms-back
+
 source venv/bin/activate
 
 set -a

+ 18 - 3
script/send_sms.py

@@ -1,4 +1,6 @@
 import os
+import logging
+import time
 import requests
 from .KdeConnect import KDEConnect
 
@@ -18,7 +20,7 @@ def send_sms_from_api(url: str, login: str, pwd: str, device_name: str):
     # List SMS to be send
     response = requests.get(url + "/sms/to-send", headers=headers)
     sms_list: list[SMSResponse] = [SMSResponse.parse_obj(obj) for obj in response.json()]
-    print(sms_list)
+    logging.info(f"{len(sms_list):5} SMS a envoyer")
     # Init KDE Connect
     kde = KDEConnect(device_name=device_name)
 
@@ -28,7 +30,7 @@ def send_sms_from_api(url: str, login: str, pwd: str, device_name: str):
             kde.send_sms(sms.phone_number, sms.content)
             requests.post(url + "/sms/send-now/" + sms.id, headers=headers)
         except Exception as exc:
-            print(exc)
+            logging.warning(f"Echec lors de l'envoie du sms {sms.id}\n{str(exc)}")
 
 
 class InvalidEnvironnementVariable(Exception):
@@ -52,4 +54,17 @@ def main():
 
 
 if __name__ == "__main__":
-    main()
+    logging.basicConfig(
+        format="%(asctime)s %(levelname)s - %(message)s",
+        level=logging.DEBUG,
+        filemode="a",
+        filename="log.txt",
+    )
+    while True:
+        starting_time = time.time()
+        try:
+            main()
+        except Exception as e:
+            logging.exception("An error as occured : ")
+        elapsed_time = time.time() - starting_time
+        time.sleep(300 - elapsed_time)