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