BAPSicle/helpers/logging_manager.py

52 lines
1.5 KiB
Python
Raw Normal View History

2020-10-30 22:00:30 +00:00
import logging
from logging.handlers import RotatingFileHandler
2020-10-30 22:00:30 +00:00
from helpers.os_environment import resolve_external_file_path
import os
2020-10-30 22:00:30 +00:00
LOG_MAX_SIZE_MB = 20
LOG_BACKUP_COUNT = 4
2020-10-30 22:00:30 +00:00
class LoggingManager():
2020-12-19 14:57:37 +00:00
logger: logging.Logger
2020-10-30 22:00:30 +00:00
2020-12-19 14:57:37 +00:00
def __init__(self, name: str):
2020-10-30 22:00:30 +00:00
self.logger = logging.getLogger(name)
logpath: str = resolve_external_file_path("/logs")
if not os.path.isdir(logpath):
try:
# Try creating the directory.
os.mkdir(logpath)
except:
print("Failed to create log directory.")
return
filename: str = resolve_external_file_path("/logs/" + name + ".log")
if not os.path.isfile(filename):
try:
# Try creating the file.
open(filename, "x")
2020-11-09 00:10:36 +00:00
except:
print("Failed to create log file.")
return
2021-02-13 15:38:26 +00:00
self.logger.setLevel(logging.INFO)
fh = RotatingFileHandler(filename, maxBytes=LOG_MAX_SIZE_MB*(1024**2), backupCount=LOG_BACKUP_COUNT)
2021-02-13 15:38:26 +00:00
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')
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
#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