Logging made better part 2

This commit is contained in:
Profitroll 2022-08-11 12:01:31 +02:00
parent 617e14f680
commit dd9ca838f7
5 changed files with 24 additions and 16 deletions

View File

@ -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",

View File

@ -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",

View File

@ -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 надано, основний скрипт не запускається",

15
main.py
View File

@ -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)

View File

@ -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)