From dd9ca838f7fed6331f71a9ad505f3a37725e985d Mon Sep 17 00:00:00 2001 From: profitroll Date: Thu, 11 Aug 2022 12:01:31 +0200 Subject: [PATCH] Logging made better part 2 --- config.json | 7 +++++-- locale/en.json | 3 ++- locale/uk.json | 3 ++- main.py | 15 +++++++++------ modules/logging.py | 12 ++++++------ 5 files changed, 24 insertions(+), 16 deletions(-) diff --git a/config.json b/config.json index dcd7b39..9c0af27 100644 --- a/config.json +++ b/config.json @@ -14,11 +14,14 @@ "startup": true, "shutdown": true }, + "logging": { + "size": 512, + "location": "logs" + }, "locations": { - "logs": "logs", "data": "data", - "queue": "data/queue", "sent": "data/sent", + "queue": "data/queue", "index": "data/index.json", "submit": "data/submit.json", "blocked": "data/blocked.json", diff --git a/locale/en.json b/locale/en.json index 102464f..7a3e5ca 100644 --- a/locale/en.json +++ b/locale/en.json @@ -43,7 +43,8 @@ "startup":"Starting with pid {0}", "keyboard_interrupt": "\nShutting down...", "exception_occured": "Exception {0} happened on task execution", - "post_exception": "Could not send content due to {0}\nTraceback: {1}", + "post_sent": "Sent {0} of type {1} to {2} with caption {3} and silently {4}", + "post_exception": "Could not send content due to {0}. Traceback: {1}", "post_empty": "Could not send content due to queue folder empty with allowed extensions", "deps_missing": "Required modules are not installed. Run 'pip3 install -r requirements.txt' and restart the program.", "passed_norun": "Argument --norun passed, not running the main script", diff --git a/locale/uk.json b/locale/uk.json index 4e931d7..53645ba 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -43,7 +43,8 @@ "startup": "Запуск бота з підом {0}", "keyboard_interrupt": "\nВимикаюсь...", "exception_occured": "Помилка {0} сталась під час виконання", - "post_exception": "Не вдалося надіслати контент через {0}\nTraceback: {1}", + "post_sent": "Надіслано {0} типу {1} у {2} з підписом {3} та без звуку {4}", + "post_exception": "Не вдалося надіслати контент через {0}. Traceback: {1}", "post_empty": "Не вдалося надіслати контент через порожню папку черги з дозволеними розширеннями", "deps_missing": "Необхідні модулі не встановлені. Запустіть 'pip3 install -r requirements.txt' і перезапустіть програму.", "passed_norun": "Аргумент --norun надано, основний скрипт не запускається", diff --git a/main.py b/main.py index 855dbc8..9d8d20b 100644 --- a/main.py +++ b/main.py @@ -1,7 +1,6 @@ import os import random import shutil -import subprocess import sys from threading import Thread import time @@ -153,31 +152,35 @@ def send_content(): if configGet("move_sent", "posting"): shutil.move(candidate, configGet("sent", "locations")+os.sep+candidate_file) + logWrite(locale("post_sent", "console", locale=configGet("locale")).format(candidate, ext_type, str(configGet("channel", "posting")), caption.replace("\n", "%n"), str(configGet("silent", "posting")))) + if configGet("sent", "reports"): app.send_message(configGet("admin"), f"Posted `{candidate_file}`", disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([ - [InlineKeyboardButton("View in channel", url=sent.link)] # type: ignore + [InlineKeyboardButton(locale("post_view", "button", locale=configGet("locale")), url=sent.link)] # type: ignore ])) # type: ignore except Exception as exp: - logWrite(f"Could not send content due to {exp}\nTraceback: {traceback.format_exc()}") + logWrite(locale("post_exception", "console", locale=configGet("locale")).format(str(exp), traceback.format_exc())) if configGet("error", "reports"): app.send_message(configGet("admin"), locale("post_exception", "message", locale=configGet("locale")).format(exp, traceback.format_exc())) # type: ignore + pass @app.on_message(~ filters.scheduled & filters.command(["start"], prefixes="/")) -def start(app, msg): +def cmd_start(app, msg): if msg.from_user.id not in jsonLoad(configGet("blocked", "locations")): msg.reply_text(locale("start", "message", locale=msg.from_user.language_code)) @app.on_message(~ filters.scheduled & filters.command(["rules", "help"], prefixes="/")) -def start(app, msg): +def cmd_rules(app, msg): if msg.from_user.id not in jsonLoad(configGet("blocked", "locations")): msg.reply_text(locale("rules", "message", locale=msg.from_user.language_code)) @app.on_message(~ filters.scheduled & filters.command(["kill", "die", "reboot"], prefixes=["", "/"])) -def kill(app, msg): +def cmd_kill(app, msg): if msg.from_user.id == configGet("admin"): + logWrite(locale("shutdown", "console", locale=configGet("locale")).format(str(pid))) msg.reply_text(locale("shutdown", "message", locale=configGet("locale")).format(str(pid))) killProc(pid) diff --git a/modules/logging.py b/modules/logging.py index 43ec709..f723db6 100644 --- a/modules/logging.py +++ b/modules/logging.py @@ -5,10 +5,10 @@ import shutil from datetime import datetime -log_size = 512 - -with open("config.json", "r", encoding='utf8') as file: - log_folder = json.loads(file.read())["locations"]["logs"] +with open(os.getcwd()+os.path.sep+"config.json", "r", encoding='utf8') as file: + json_contents = json.loads(file.read()) + log_size = json_contents["logging"]["size"] + log_folder = json_contents["logging"]["location"] file.close() # Check latest log size @@ -26,7 +26,7 @@ def checkSize(): print(f'Copied {os.path.join(log_folder, datetime.now().strftime("%d.%m.%Y_%H:%M:%S"))}.log.gz') open(os.path.join(log_folder, "latest.log"), 'w').close() except FileNotFoundError: - print('Not found') + print(f'Log file {os.path.join(log_folder, "latest.log")} does not exist') pass # Append string to log @@ -44,5 +44,5 @@ def logAppend(message): # Print to stdout and then to log def logWrite(message): # save to log file and rotation is to be done - logAppend(f'[{datetime.now().strftime("%d.%m.%Y")}] [{datetime.now().strftime("%H:%M:%S")}] {message}', flush=True) + logAppend(f'{message}') print(f"{message}", flush=True) \ No newline at end of file