Add logrotate and create dir if missing.

This commit is contained in:
Matthew Stratford 2021-04-05 22:41:22 +01:00
parent 5d353f4134
commit c406d998f3
3 changed files with 18 additions and 5 deletions

View file

@ -1,7 +1,10 @@
import logging
from logging.handlers import RotatingFileHandler
from helpers.os_environment import resolve_external_file_path
import os
LOG_MAX_SIZE_MB = 20
LOG_BACKUP_COUNT = 4
class LoggingManager():
@ -10,6 +13,16 @@ class LoggingManager():
def __init__(self, name: str):
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):
@ -17,12 +30,12 @@ class LoggingManager():
# Try creating the file.
open(filename, "x")
except:
print("Failed to create log file")
print("Failed to create log file.")
return
self.logger.setLevel(logging.INFO)
fh = logging.FileHandler(filename)
fh = RotatingFileHandler(filename, maxBytes=LOG_MAX_SIZE_MB*(1024**2), backupCount=LOG_BACKUP_COUNT)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')
fh.setFormatter(formatter)
# add the handler to the logger

2
logs/.gitignore vendored
View file

@ -1 +1 @@
*.log
*.log*

View file

@ -504,11 +504,11 @@ class Player():
self.running = True
self.out_q = out_q
self.logger = LoggingManager("channel" + str(channel))
self.logger = LoggingManager("Player" + str(channel))
self.api = MyRadioAPI(self.logger)
self.state = StateManager("channel" + str(channel), self.logger,
self.state = StateManager("Player" + str(channel), self.logger,
self.__default_state, self.__rate_limited_params)
self.state.add_callback(self._send_status)