2020-10-30 22:00:30 +00:00
|
|
|
import logging
|
2021-04-05 21:41:22 +00:00
|
|
|
from logging.handlers import RotatingFileHandler
|
2022-03-11 23:29:46 +00:00
|
|
|
from typing import Optional
|
2020-10-30 22:00:30 +00:00
|
|
|
from helpers.os_environment import resolve_external_file_path
|
2020-11-08 23:38:57 +00:00
|
|
|
import os
|
2022-03-11 23:29:46 +00:00
|
|
|
import package
|
2020-10-30 22:00:30 +00:00
|
|
|
|
2021-04-05 21:41:22 +00:00
|
|
|
LOG_MAX_SIZE_MB = 20
|
|
|
|
LOG_BACKUP_COUNT = 4
|
2020-10-30 22:00:30 +00:00
|
|
|
|
2021-04-08 19:53:51 +00:00
|
|
|
|
|
|
|
class LoggingManager:
|
2020-10-30 22:00:30 +00:00
|
|
|
|
2020-12-19 14:57:37 +00:00
|
|
|
logger: logging.Logger
|
2020-10-30 22:00:30 +00:00
|
|
|
|
2022-03-11 23:29:46 +00:00
|
|
|
def __init__(self, name: str, debug: Optional[bool] = None):
|
2020-10-30 22:00:30 +00:00
|
|
|
self.logger = logging.getLogger(name)
|
|
|
|
|
2021-04-05 21:41:22 +00:00
|
|
|
logpath: str = resolve_external_file_path("/logs")
|
|
|
|
if not os.path.isdir(logpath):
|
|
|
|
try:
|
|
|
|
# Try creating the directory.
|
|
|
|
os.mkdir(logpath)
|
2021-04-08 21:32:16 +00:00
|
|
|
except Exception:
|
2021-04-05 21:41:22 +00:00
|
|
|
print("Failed to create log directory.")
|
|
|
|
return
|
|
|
|
|
2020-11-08 23:38:57 +00:00
|
|
|
filename: str = resolve_external_file_path("/logs/" + name + ".log")
|
|
|
|
|
|
|
|
if not os.path.isfile(filename):
|
|
|
|
try:
|
|
|
|
# Try creating the file.
|
2021-04-07 20:22:11 +00:00
|
|
|
file = open(filename, "x")
|
|
|
|
file.close()
|
2021-04-08 21:32:16 +00:00
|
|
|
except Exception:
|
2021-04-05 21:41:22 +00:00
|
|
|
print("Failed to create log file.")
|
2020-11-08 23:38:57 +00:00
|
|
|
return
|
|
|
|
|
2022-03-11 23:29:46 +00:00
|
|
|
# Enable debug by default
|
2022-03-11 23:55:53 +00:00
|
|
|
if (debug is None and package.BETA):
|
2022-03-11 23:29:46 +00:00
|
|
|
debug = True
|
|
|
|
|
2021-05-02 01:26:55 +00:00
|
|
|
self.logger.setLevel(logging.DEBUG if debug else logging.INFO)
|
2021-04-08 19:53:51 +00:00
|
|
|
fh = RotatingFileHandler(
|
|
|
|
filename,
|
|
|
|
maxBytes=LOG_MAX_SIZE_MB * (1024 ** 2),
|
|
|
|
backupCount=LOG_BACKUP_COUNT,
|
|
|
|
)
|
|
|
|
formatter = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
|
2021-02-13 15:38:26 +00:00
|
|
|
fh.setFormatter(formatter)
|
|
|
|
# add the handler to the logger
|
|
|
|
self.logger.addHandler(fh)
|
2020-10-30 23:59:58 +00:00
|
|
|
self.logger.info("** LOGGER STARTED **")
|
2020-10-30 22:00:30 +00:00
|
|
|
|
2021-04-08 19:53:51 +00:00
|
|
|
# def __del__(self):
|
|
|
|
# Can't seem to close logger properly
|
|
|
|
# self.logger.info("** LOGGER EXITING **")
|
2020-10-30 22:00:30 +00:00
|
|
|
|
|
|
|
@property
|
2020-12-19 14:57:37 +00:00
|
|
|
def log(self) -> logging.Logger:
|
2020-10-30 22:00:30 +00:00
|
|
|
return self.logger
|