Only format file log, add tests

This commit is contained in:
Joe Knapper 2026-07-07 14:47:53 +01:00
parent e42aaf2547
commit 013341272e
2 changed files with 56 additions and 15 deletions

View file

@ -52,8 +52,8 @@ def configure_logging(log_folder: str, debug: bool = False) -> None:
# Add OFM_HANDLER first so it can capture the error log if the
# log file can't be accessed.
ofm_format_str = "[%(asctime)s] [%(levelname)s]%(invocation_id_str)s %(message)s"
OFM_HANDLER.setFormatter(OFMConsoleFormatter(ofm_format_str))
ofm_format_str = "[%(asctime)s] [%(levelname)s] %(message)s"
OFM_HANDLER.setFormatter(logging.Formatter(ofm_format_str))
OFM_HANDLER.addFilter(UvicornAccessFilter())
OFM_HANDLER.addFilter(inject_invocation_id)
OFM_HANDLER.level = root_logger.level
@ -120,7 +120,10 @@ def retrieve_log_from_file() -> PlainTextResponse:
class OFMLogFileFormatter(logging.Formatter):
"""The formatter used for the OpenFlexure Microscope Server log file."""
"""The formatter used for the OpenFlexure Microscope Server log file.
This is the log that is then read by the GUI.
"""
def format(self, record: logging.LogRecord) -> str:
"""Adjust the logging formatting for uvicorn logs.
@ -131,6 +134,11 @@ class OFMLogFileFormatter(logging.Formatter):
such as server start up. This can lead to people erroneously thinking that
there is an error with their miroscope.
"""
invocation_id = getattr(record, "invocation_id", None)
record.invocation_id_str = (
f" [invocation:{invocation_id}]" if invocation_id else ""
)
if record.name == "uvicorn.error" and record.levelno < logging.ERROR:
record.name = "uvicorn"
return super().format(record)
@ -188,16 +196,4 @@ class UvicornAccessFilter(logging.Filter):
return not record.name.startswith("uvicorn.access")
class OFMConsoleFormatter(logging.Formatter):
"""Formatter for OFM_HANDLER (the UI-facing log)."""
def format(self, record: logging.LogRecord) -> str:
"""Render the invocation ID into the record, if present."""
invocation_id = getattr(record, "invocation_id", None)
record.invocation_id_str = (
f" [invocation:{invocation_id}]" if invocation_id else ""
)
return super().format(record)
OFM_HANDLER = OFMHandler()