Add HookableInMemoryHandler logging handler

This commit is contained in:
Kangwook Lee 2021-08-02 03:19:43 +09:00 committed by Dan Albert
parent 6621421a6f
commit 6ee0c7600b
3 changed files with 54 additions and 5 deletions

2
.gitignore vendored
View File

@ -18,7 +18,7 @@ env/
/liberation_preferences.json /liberation_preferences.json
/state.json /state.json
logs/ /logs/
qt_ui/logs/liberation.log qt_ui/logs/liberation.log

View File

@ -3,6 +3,8 @@ import logging
import os import os
from logging.handlers import RotatingFileHandler from logging.handlers import RotatingFileHandler
from qt_ui.logging_handler import HookableInMemoryHandler
def init_logging(version: str) -> None: def init_logging(version: str) -> None:
"""Initializes the logging configuration.""" """Initializes the logging configuration."""
@ -10,13 +12,22 @@ def init_logging(version: str) -> None:
os.mkdir("logs") os.mkdir("logs")
fmt = "%(asctime)s :: %(levelname)s :: %(message)s" fmt = "%(asctime)s :: %(levelname)s :: %(message)s"
formatter = logging.Formatter(fmt)
logging.basicConfig(level=logging.DEBUG, format=fmt) logging.basicConfig(level=logging.DEBUG, format=fmt)
logger = logging.getLogger() logger = logging.getLogger()
handler = RotatingFileHandler("./logs/liberation.log", "a", 5000000, 1) rotating_file_handler = RotatingFileHandler(
handler.setLevel(logging.DEBUG) "./logs/liberation.log", "a", 5000000, 1
handler.setFormatter(logging.Formatter(fmt)) )
rotating_file_handler.setLevel(logging.DEBUG)
rotating_file_handler.setFormatter(formatter)
logger.addHandler(handler) hookable_in_memory_handler = HookableInMemoryHandler()
hookable_in_memory_handler.setLevel(logging.DEBUG)
hookable_in_memory_handler.setFormatter(formatter)
logger.addHandler(rotating_file_handler)
logger.addHandler(hookable_in_memory_handler)
logger.info(f"DCS Liberation {version}") logger.info(f"DCS Liberation {version}")

38
qt_ui/logging_handler.py Normal file
View File

@ -0,0 +1,38 @@
import logging
import typing
LogHook = typing.Callable[[str], None]
class HookableInMemoryHandler(logging.Handler):
"""Hookable in-memory logging handler for logs window"""
_log: str
_hook: typing.Optional[typing.Callable[[str], None]]
def __init__(self, *args, **kwargs):
super(HookableInMemoryHandler, self).__init__(*args, **kwargs)
self._log = ""
self._hook = None
@property
def log(self) -> str:
return self._log
def emit(self, record):
msg = self.format(record)
self._log += msg + "\n"
if self._hook is not None:
self._hook(msg)
def write(self, m):
pass
def clearLog(self) -> None:
self._log = ""
def setHook(self, hook: typing.Callable[[str], None]) -> None:
self._hook = hook
def clearHook(self) -> None:
self._hook = None