myTS3/src/util.py

106 lines
2.5 KiB
Python

"""
TBD
"""
__author__ = "Lukas Mahler"
__version__ = "1.0.0"
__date__ = "14.04.2022"
__email__ = "m@hler.eu"
__status__ = "Development"
# Default
import sys
import shutil
import os.path
import logging
import time
from datetime import timedelta
from logging.handlers import RotatingFileHandler
# Custom
import toml
def unhandledException(exc_type, exc_value, exc_traceback):
"""
src = https://stackoverflow.com/a/16993115/5593051
"""
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
log.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
def getConf(fname):
"""
"""
if fname.endswith(".toml"):
if os.path.isfile(fname):
try:
config = toml.load(fname)
checkConf(config)
return config
except ValueError as e:
log.critical(f"The provided '.toml' is probably invalid, returned error:\n{e}")
exit(1)
else:
log.critical(f"Couldn't locate the '.toml' file [{fname}].")
log.info("Creating a new '.toml' file from template, please edit and restart.")
shutil.copy("src/template.toml", fname)
exit(1)
else:
log.critical(f"The provided config file [{fname}] is not a '.toml' file.")
log.info("Creating a new '.toml' file from template, please edit and restart.")
shutil.copy("src/template.toml", "prod.toml")
exit(1)
def getRuntime(started):
"""
"""
elapsed = time.time() - started
runtime = str(timedelta(seconds=elapsed)).split(".")[0] # ignore Microseconds
return runtime
def checkConf(config):
"""
TODO check if keys exist
"""
pass
def setupLogger(logpath, lvl="DEBUG"):
"""
Create a rotating log in a log folder
"""
global log # Needed to log exceptions in src\util
log = logging.getLogger("mylog")
if not os.path.exists(logpath):
os.makedirs(logpath)
handler = RotatingFileHandler(logpath + r"/myTS3.log", encoding='utf-8', maxBytes=1*1024*1024, backupCount=10)
logformat = logging.Formatter("%(asctime)s %(levelname)8s %(message)s", "%Y-%m-%d %H:%M:%S")
handler.setFormatter(logformat)
log.addHandler(handler)
log.setLevel(logging.getLevelName(lvl))
return log
def changeLevel(log, lvl):
"""
Change the loglevel after creation
"""
log.setLevel(logging.getLevelName(lvl))
if __name__ == "__main__":
exit()