Logging made better part 1
This commit is contained in:
parent
f4dca4164c
commit
617e14f680
@ -15,6 +15,7 @@
|
||||
"shutdown": true
|
||||
},
|
||||
"locations": {
|
||||
"logs": "logs",
|
||||
"data": "data",
|
||||
"queue": "data/queue",
|
||||
"sent": "data/sent",
|
||||
|
@ -1,4 +1,48 @@
|
||||
import os
|
||||
import gzip
|
||||
import json
|
||||
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"]
|
||||
file.close()
|
||||
|
||||
# Check latest log size
|
||||
def checkSize():
|
||||
|
||||
global log_folder
|
||||
|
||||
try:
|
||||
os.makedirs(log_folder, exist_ok=True)
|
||||
log = os.stat(os.path.join(log_folder, "latest.log"))
|
||||
if (log.st_size / 1024) > log_size:
|
||||
with open(os.path.join(log_folder, "latest.log"), 'rb') as f_in:
|
||||
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')
|
||||
open(os.path.join(log_folder, "latest.log"), 'w').close()
|
||||
except FileNotFoundError:
|
||||
print('Not found')
|
||||
pass
|
||||
|
||||
# Append string to log
|
||||
def logAppend(message):
|
||||
|
||||
global log_folder
|
||||
|
||||
message_formatted = f'[{datetime.now().strftime("%d.%m.%Y")}] [{datetime.now().strftime("%H:%M:%S")}] {message}'
|
||||
checkSize()
|
||||
|
||||
log = open(os.path.join(log_folder, "latest.log"), 'a')
|
||||
log.write(f'{message_formatted}\n')
|
||||
log.close()
|
||||
|
||||
# Print to stdout and then to log
|
||||
def logWrite(message):
|
||||
# save to log file and rotation is to be done
|
||||
# logAppend(f"[{nowtime()}] {message}", flush=True)
|
||||
logAppend(f'[{datetime.now().strftime("%d.%m.%Y")}] [{datetime.now().strftime("%H:%M:%S")}] {message}', flush=True)
|
||||
print(f"{message}", flush=True)
|
Reference in New Issue
Block a user