try: from ujson import loads except ModuleNotFoundError: from json import loads from os import stat, makedirs, path, getcwd from gzip import open as gzipopen from shutil import copyfileobj from datetime import datetime with open(getcwd()+path.sep+"config.json", "r", encoding='utf8') as file: json_contents = loads(file.read()) log_size = json_contents["logging"]["size"] log_folder = json_contents["logging"]["location"] file.close() # Check latest log size def checkSize(debug=False): global log_folder if debug: log_file = "debug.log" else: log_file = "latest.log" try: makedirs(log_folder, exist_ok=True) log = stat(path.join(log_folder, log_file)) 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: 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() except FileNotFoundError: print(f'Log file {path.join(log_folder, log_file)} does not exist') pass # Append string to log def logAppend(message, debug=False): 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" log = open(path.join(log_folder, log_file), 'a') log.write(f'{message_formatted}\n') log.close() # Print to stdout and then to log def logWrite(message, debug=False): # save to log file and rotation is to be done logAppend(f'{message}', debug=debug) print(f"{message}", flush=True)