logging enhancements

This commit is contained in:
Piotr Dec 2025-10-22 22:53:49 +02:00
parent 2dec6d5384
commit 569aefeccb
Signed by: stawros
GPG key ID: 74B18A3F0F1E99C0
8 changed files with 88 additions and 20 deletions

View file

@ -1,4 +1,8 @@
from logging import Formatter, StreamHandler
from enum import Enum, auto
from logging import Formatter, StreamHandler, Handler
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
from typing import List
class NamingCache:
@ -37,7 +41,7 @@ class ApplicationFormatter(Formatter):
from datetime import datetime
timestamp = datetime.fromtimestamp(record.created).isoformat(sep=' ', timespec='milliseconds')
level = record.levelname.replace('WARNING', 'WARN').rjust(5)
thread_name = record.threadName.replace(' (', '#').replace(')', '').rjust(16)[-16:] # TODO: NamingCache?
thread_name = record.threadName.replace(' (', '#').replace(')', '').rjust(16)[-16:] # TODO: NamingCache?
logger_name = self._logger_names[f"{self._handler_prefix}{record.name}"]
message = record.getMessage()
formatted = f"{timestamp} {level} [{thread_name}] {logger_name} : {message}"
@ -48,12 +52,35 @@ class ApplicationFormatter(Formatter):
return formatted
class LoggingHandler(StreamHandler):
def __init__(self):
super().__init__()
self.setFormatter(ApplicationFormatter(handler_prefix='karl.'))
class HandlerFactory:
class Target(Enum):
CONSOLE = auto()
FILE = auto()
ALL = auto()
class ExternalLoggingHandler(StreamHandler):
def __init__(self):
super().__init__()
self.setFormatter(ApplicationFormatter())
@staticmethod
def create(target: Target, handler_prefix: str = '', file_path: Path = None) -> List[Handler]:
def console_handler(prefix: str = ''):
handler = StreamHandler()
handler.setFormatter(ApplicationFormatter(prefix))
handler.setLevel('INFO')
return handler
def file_handler(prefix: str = ''):
handler = TimedRotatingFileHandler(file_path, when='midnight', backupCount=30)
handler.setFormatter(ApplicationFormatter(prefix))
handler.setLevel('TRACE')
return handler
handlers = []
match target:
case HandlerFactory.Target.CONSOLE:
handlers.append(console_handler(handler_prefix))
case HandlerFactory.Target.FILE:
handlers.append(file_handler(handler_prefix))
case HandlerFactory.Target.ALL:
handlers.append(file_handler(handler_prefix))
handlers.append(console_handler(handler_prefix))
case _:
raise ValueError(f"Unknown target: {target}")
return handlers