use tempfile in add_file_log and add_console_log

- when running from an account that cannot write
  in the expected folder it uses tempfile to
  create a temporary file instead
This commit is contained in:
Unknown MX Person 2024-08-07 14:34:39 +02:00 committed by wakonig_k
parent 4af3e0e94d
commit e169696473

View File

@ -220,13 +220,23 @@ class BECLogger:
""" """
if not self.service_name: if not self.service_name:
return return
filename = os.path.join(self._base_path, f"{self.service_name}.log") try:
self.logger.add( filename = os.path.join(self._base_path, f"{self.service_name}.log")
filename, self.logger.add(
level=level, filename,
format=self.formatting, level=level,
filter=lambda record: record["level"].no != LogLevel.CONSOLE_LOG, format=self.formatting,
) filter=lambda record: record["level"].no != LogLevel.CONSOLE_LOG,
)
except PermissionError:
import tempfile
filename = tempfile.NamedTemporaryFile(prefix=self.service_name, delete=False, mode="a+")
self.logger.add(
filename,
level=level,
format=self.formatting,
filter=lambda record: record["level"].no != LogLevel.CONSOLE_LOG,
)
def add_console_log(self): def add_console_log(self):
""" """
@ -234,7 +244,6 @@ class BECLogger:
""" """
if not self.service_name: if not self.service_name:
return return
filename = os.path.join(self._base_path, f"{self.service_name}_CONSOLE.log")
# define a level corresponding to console log - this is to be able to filter messages # define a level corresponding to console log - this is to be able to filter messages
# (only those with this particular level will be recorded by the console logger, # (only those with this particular level will be recorded by the console logger,
@ -245,12 +254,24 @@ class BECLogger:
# level with same severity already exists: already configured # level with same severity already exists: already configured
pass pass
self.logger.add( try:
filename, filename = os.path.join(self._base_path, f"{self.service_name}_CONSOLE.log")
level=LogLevel.CONSOLE_LOG, self.logger.add(
format=self.get_format(LogLevel.CONSOLE_LOG).rstrip(), filename,
filter=lambda record: record["level"].no == LogLevel.CONSOLE_LOG, level=LogLevel.CONSOLE_LOG,
) format=self.get_format(LogLevel.CONSOLE_LOG).rstrip(),
filter=lambda record: record["level"].no == LogLevel.CONSOLE_LOG,
)
except PermissionError:
import tempfile
filename = tempfile.NamedTemporaryFile(suffix=f"{self.service_name}_CONSOLE.log", delete=False, mode="a+")
self.logger.add(
filename,
level=LogLevel.CONSOLE_LOG,
format=self.get_format(LogLevel.CONSOLE_LOG).rstrip(),
filter=lambda record: record["level"].no == LogLevel.CONSOLE_LOG,
)
self._console_log = True self._console_log = True
def add_redis_log(self, level: LogLevel): def add_redis_log(self, level: LogLevel):