diff --git a/software/control/core/fluidics_protocol/logger_names.py b/software/control/core/fluidics_protocol/logger_names.py new file mode 100644 index 0000000000..2f42323f41 --- /dev/null +++ b/software/control/core/fluidics_protocol/logger_names.py @@ -0,0 +1,22 @@ +"""The loggers whose records are fluidics, for the logs that keep fluidics apart from the rest of Squid's +logging: the protocol run's run.log and the GUI's Fluidics Log pane. No Qt and no fluidics library import, so +both work when the library is not installed.""" + +import logging +from typing import List + +import squid.logging + +# The fluidics library's own loggers. control.fluidics_system's logging bridge hands their records to the squid +# root logger's handlers, and the records keep these names. +LIBRARY_LOGGER_NAMES = ("fluidics", "XCaliburD") + +# Squid's fluidics packages, under the squid root logger. +SQUID_FLUIDICS_LOGGER_NAMES = ("control.widgets_fluidics", "control.core.fluidics_protocol", "control.fluidics_system") + + +def fluidics_loggers() -> List[logging.Logger]: + """The top fluidics loggers; a record is fluidics when its logger is one of these or below one.""" + return [logging.getLogger(name) for name in LIBRARY_LOGGER_NAMES] + [ + squid.logging.get_logger(name) for name in SQUID_FLUIDICS_LOGGER_NAMES + ] diff --git a/software/control/core/fluidics_protocol/runner.py b/software/control/core/fluidics_protocol/runner.py index 08d16cbd07..7d341b6867 100644 --- a/software/control/core/fluidics_protocol/runner.py +++ b/software/control/core/fluidics_protocol/runner.py @@ -6,6 +6,7 @@ only writer of run_manifest.json, and never opens a dialog - the GUI adapts its events (phase 2). """ +import logging import os import threading import time @@ -14,6 +15,7 @@ from typing import Optional, Tuple import squid.logging +from control.core.fluidics_protocol.logger_names import fluidics_loggers from control.core.fluidics_protocol import manifest as manifest_io from control.core.fluidics_protocol.events import ( Hold, @@ -69,6 +71,19 @@ class _StepResult: can_accept: bool = False +class _RunLogFilter(logging.Filter): + """What run.log keeps: every fluidics record, DEBUG included, and the rest of Squid at INFO and above.""" + + def __init__(self): + super().__init__() + self._fluidics_names = tuple(logger.name for logger in fluidics_loggers()) + + def filter(self, record: logging.LogRecord) -> bool: + if record.levelno >= logging.INFO: + return True + return any(record.name == name or record.name.startswith(name + ".") for name in self._fluidics_names) + + class ProtocolRunner: def __init__( self, @@ -231,8 +246,13 @@ def _run(self) -> None: def _open_run(self) -> None: self.run_dir.mkdir(parents=True, exist_ok=True) try: + # run.log is the record for debugging the run's fluidics: all fluidics DEBUG, the rest of Squid at + # INFO and above. The handler sits on the squid root logger, and without the filter it copied all of + # Squid's DEBUG traffic (Timer, MCU) for the whole run; that is still in main_hcs.log. self._log_handler = squid.logging.add_file_handler( - str(self.run_dir / manifest_io.RUN_LOG_NAME), replace_existing=True + str(self.run_dir / manifest_io.RUN_LOG_NAME), + replace_existing=True, + record_filter=_RunLogFilter(), ) except Exception: self._log.exception("Could not open run.log") diff --git a/software/control/fluidics_system.py b/software/control/fluidics_system.py index 5dada2b18c..2ff2cc6346 100644 --- a/software/control/fluidics_system.py +++ b/software/control/fluidics_system.py @@ -15,6 +15,7 @@ from typing import List, Optional, Tuple import squid.logging +from control.core.fluidics_protocol.logger_names import LIBRARY_LOGGER_NAMES try: from fluidics.control.config import load_config @@ -30,8 +31,6 @@ _log = squid.logging.get_logger(__name__) -LIBRARY_LOGGER_NAMES = ("fluidics", "XCaliburD") - _REQUIRED_SYSTEM_API = ( "build", "plan", diff --git a/software/control/widgets_fluidics/log_view.py b/software/control/widgets_fluidics/log_view.py index 5fa7fe1a6c..40c90d9644 100644 --- a/software/control/widgets_fluidics/log_view.py +++ b/software/control/widgets_fluidics/log_view.py @@ -25,6 +25,7 @@ ) import squid.logging +from control.core.fluidics_protocol.logger_names import fluidics_loggers _LEVELS = {"INFO": logging.INFO, "DEBUG": logging.DEBUG} @@ -59,26 +60,13 @@ def __init__(self, parent=None): layout.addWidget(self.text_edit) self.setLayout(layout) - def _fluidics_loggers(self) -> list: - """The loggers whose subtrees are fluidics — the library's (forwarded records keep - their own names) and Squid's fluidics packages. Records propagate up to a handler - here, so the pane catches fluidics only without touching the rest of Squid.""" - # The two library names mirror control.fluidics_system.LIBRARY_LOGGER_NAMES; kept as - # literals on purpose so this pane (and its tests) stay importable when the fluidics - # library isn't installed. If that tuple gains a logger, add it here too. - return [ - logging.getLogger("fluidics"), - logging.getLogger("XCaliburD"), - squid.logging.get_logger("control.widgets_fluidics"), - squid.logging.get_logger("control.core.fluidics_protocol"), - squid.logging.get_logger("control.fluidics_system"), - ] - def connect_logging(self) -> None: - """Attach the buffering handler to the fluidics loggers and start polling. GUI thread only.""" + """Attach the buffering handler to the fluidics loggers and start polling. GUI thread only. + Records propagate up to a handler there, so the pane catches fluidics only without touching + the rest of Squid.""" self.disconnect_logging() self._handler = squid.logging.BufferingHandler(min_level=_LEVELS[self.level_combo.currentText()]) - for logger in self._fluidics_loggers(): + for logger in fluidics_loggers(): logger.addHandler(self._handler) self._poll_timer = QTimer(self) self._poll_timer.timeout.connect(self._poll) @@ -89,7 +77,7 @@ def disconnect_logging(self) -> None: self._poll_timer.stop() self._poll_timer = None if self._handler is not None: - for logger in self._fluidics_loggers(): + for logger in fluidics_loggers(): logger.removeHandler(self._handler) self._handler = None diff --git a/software/docs/fluidics-protocol.md b/software/docs/fluidics-protocol.md index 24e4533ae0..0383333a08 100644 --- a/software/docs/fluidics-protocol.md +++ b/software/docs/fluidics-protocol.md @@ -104,7 +104,7 @@ Slack when the notifier is configured. {run_name}_{YYYY-MM-DD_HH-MM-SS}/ ├── protocol.yaml exactly what ran (file-based blocks inlined) ├── run_manifest.json status, cursor, per-step attempts, TEC state, pid + heartbeat -├── run.log protocol + fluidics log for the whole run +├── run.log protocol + fluidics log for the whole run (fluidics at DEBUG, the rest of Squid at INFO and above; all of it is in main_hcs.log) ├── R01_image/ a standard Squid experiment folder (+ protocol_step.json) ├── R02_image/ attempt 1 — aborted, kept, never renamed (aborted.json inside) └── R02_image_attempt2/ attempt 2 — completed diff --git a/software/squid/logging.py b/software/squid/logging.py index 5dd70b708a..7f2d2c5574 100644 --- a/software/squid/logging.py +++ b/software/squid/logging.py @@ -212,10 +212,13 @@ def add_file_logging(log_filename, replace_existing=False): return True -def add_file_handler(log_filename, replace_existing=False, level=py_logging.DEBUG) -> Optional[py_logging.Handler]: +def add_file_handler( + log_filename, replace_existing=False, level=py_logging.DEBUG, record_filter: Optional[py_logging.Filter] = None +) -> Optional[py_logging.Handler]: """ Attach a plain FileHandler to the squid root logger and return it, so callers can later remove/close it. - This uses the same baseline formatting + thread_id injection as squid's other logs. + This uses the same baseline formatting + thread_id injection as squid's other logs. A record_filter is + attached before the handler goes on the logger, so it applies to the file's first record too. """ root_logger = get_logger() abs_path = os.path.abspath(log_filename) @@ -242,6 +245,8 @@ def add_file_handler(log_filename, replace_existing=False, level=py_logging.DEBU new_handler.setLevel(level) new_handler.setFormatter(py_logging.Formatter(fmt=_baseline_log_format, datefmt=_baseline_log_dateformat)) new_handler.addFilter(_thread_id_filter) + if record_filter is not None: + new_handler.addFilter(record_filter) log.info(f"Adding new file handler writing to file '{abs_path}'") root_logger.addHandler(new_handler) diff --git a/software/tests/control/core/fluidics_protocol/test_runner.py b/software/tests/control/core/fluidics_protocol/test_runner.py index 16bb4c894f..1db0cbf642 100644 --- a/software/tests/control/core/fluidics_protocol/test_runner.py +++ b/software/tests/control/core/fluidics_protocol/test_runner.py @@ -1,11 +1,13 @@ import json +import logging import os from types import SimpleNamespace import pytest +import squid.logging from control.core.fluidics_protocol import manifest as manifest_io -from control.core.fluidics_protocol.events import HoldAction, RunnerState +from control.core.fluidics_protocol.events import HoldAction, RunnerState, StepStarted from control.core.fluidics_protocol.resolve import resolve_protocol from control.core.fluidics_protocol.runner import ProtocolRunner from control.models.fluidics_protocol import ProtocolFile, expand_rounds @@ -68,12 +70,13 @@ def _protocol(rounds=1): return p -def _runner(tmp_path, fluidics=None, imaging=None, rounds=1, events=None): +def _runner(tmp_path, fluidics=None, imaging=None, rounds=1, events=None, listener=None): fluidics = fluidics or FakeFluidicsPort() imaging = imaging or FakeImagingPort() resolved = resolve_protocol(_protocol(rounds), tmp_path, fluidics=fluidics) run_dir = manifest_io.create_run_dir(tmp_path, "liver") - listener = events.append if events is not None else None + if events is not None: + listener = events.append runner = ProtocolRunner(resolved, run_dir, imaging, fluidics, run_name="liver", listener=listener, poll_s=0.01) return runner, fluidics, imaging, run_dir @@ -110,6 +113,37 @@ def test_happy_path_runs_every_step_and_leaves_the_documented_run_folder(tmp_pat assert kinds[0] == "StateChanged" and kinds[-1] == "RunFinished" and kinds.count("StepStarted") == 4 +def test_run_log_keeps_fluidics_debug_and_the_rest_of_squid_at_info_and_above(tmp_path): + # run.log is the run's record for debugging fluidics: every fluidics record, DEBUG included (valve routing, + # sequence contents), and the rest of Squid at INFO and above. The rest of Squid's DEBUG (Timer, MCU) stays + # out of it. Log while the run is going, the way Squid and the library do. + other = squid.logging.get_logger("control.microcontroller") + squid_fluidics = squid.logging.get_logger("control.core.fluidics_protocol.marker") + + def listener(event): + if isinstance(event, StepStarted): + other.debug("OTHER-DEBUG-MARKER") + other.info("OTHER-INFO-MARKER") + squid_fluidics.debug("SQUID-FLUIDICS-DEBUG-MARKER") + # What control.fluidics_system's logging bridge does with a library record: hand it, under the + # library's logger name, to the squid root logger's handlers. + squid.logging.get_logger().handle( + logging.LogRecord( + "fluidics.control.selector_valve", logging.DEBUG, __file__, 0, "LIBRARY-DEBUG-MARKER", None, None + ) + ) + + runner, _fluidics, _imaging, run_dir = _runner(tmp_path, listener=listener) + runner.start() + assert runner.wait(10) and runner.outcome == "finished" + + text = (run_dir / "run.log").read_text(encoding="utf-8") + assert "OTHER-INFO-MARKER" in text + assert "SQUID-FLUIDICS-DEBUG-MARKER" in text + assert "LIBRARY-DEBUG-MARKER" in text + assert "OTHER-DEBUG-MARKER" not in text + + def test_progress_fraction_prices_elapsed_over_the_estimate(tmp_path): # the snapshot owns "how far through the run" so it's testable without the GUI: elapsed over # the rough total estimate, held just under full until the run ends, None when there's no estimate.