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/logging.py

48 lines
1.6 KiB
Python

import os
import gzip
import json
import shutil
from datetime import datetime
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
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(f'Log file {os.path.join(log_folder, "latest.log")} does not exist')
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'{message}')
print(f"{message}", flush=True)