This repository has been archived on 2024-08-21. You can view files and clone it, but cannot push or open issues or pull requests.
TelegramPoster/modules/logger.py

68 lines
2.0 KiB
Python
Raw Permalink Normal View History

from datetime import datetime
2022-08-31 15:31:24 +03:00
from gzip import open as gzipopen
from os import getcwd, makedirs, path, stat
2022-08-31 15:31:24 +03:00
from shutil import copyfileobj
2022-08-11 12:37:24 +03:00
from ujson import loads
2022-08-11 12:37:24 +03:00
with open(getcwd() + path.sep + "config.json", "r", encoding="utf8") as file:
2022-08-31 15:31:24 +03:00
json_contents = loads(file.read())
2022-08-11 13:01:31 +03:00
log_size = json_contents["logging"]["size"]
log_folder = json_contents["logging"]["location"]
2022-08-11 12:37:24 +03:00
file.close()
# Check latest log size
def checkSize(debug=False) -> None:
2022-08-11 12:37:24 +03:00
global log_folder
if debug:
log_file = "debug.log"
else:
log_file = "latest.log"
2022-08-11 12:37:24 +03:00
try:
2022-08-31 15:31:24 +03:00
makedirs(log_folder, exist_ok=True)
log = stat(path.join(log_folder, log_file))
2022-08-11 12:37:24 +03:00
if (log.st_size / 1024) > log_size:
with open(path.join(log_folder, log_file), "rb") as f_in:
with gzipopen(
path.join(
log_folder,
f'{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.log.gz',
),
"wb",
) as f_out:
2022-08-31 15:31:24 +03:00
copyfileobj(f_in, f_out)
print(
f'Copied {path.join(log_folder, datetime.now().strftime("%d.%m.%Y_%H:%M:%S"))}.log.gz'
)
open(path.join(log_folder, log_file), "w").close()
2022-08-11 12:37:24 +03:00
except FileNotFoundError:
print(f"Log file {path.join(log_folder, log_file)} does not exist")
2022-08-11 12:37:24 +03:00
pass
# Append string to log
def logAppend(message, debug=False) -> None:
2022-08-11 12:37:24 +03:00
global log_folder
message_formatted = f'[{datetime.now().strftime("%d.%m.%Y")}] [{datetime.now().strftime("%H:%M:%S")}] {message}'
checkSize(debug=debug)
if debug:
log_file = "debug.log"
else:
log_file = "latest.log"
2022-08-11 12:37:24 +03:00
log = open(path.join(log_folder, log_file), "a")
log.write(f"{message_formatted}\n")
2022-08-11 12:37:24 +03:00
log.close()
2022-08-11 12:37:24 +03:00
# Print to stdout and then to log
def logWrite(message, debug=False) -> None:
2022-08-08 15:53:26 +03:00
# save to log file and rotation is to be done
logAppend(f"{message}", debug=debug)
print(f"{message}", flush=True)