Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions software/control/core/fluidics_protocol/logger_names.py
Original file line number Diff line number Diff line change
@@ -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
]
22 changes: 21 additions & 1 deletion software/control/core/fluidics_protocol/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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")
Expand Down
3 changes: 1 addition & 2 deletions software/control/fluidics_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -30,8 +31,6 @@

_log = squid.logging.get_logger(__name__)

LIBRARY_LOGGER_NAMES = ("fluidics", "XCaliburD")

_REQUIRED_SYSTEM_API = (
"build",
"plan",
Expand Down
24 changes: 6 additions & 18 deletions software/control/widgets_fluidics/log_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
)

import squid.logging
from control.core.fluidics_protocol.logger_names import fluidics_loggers

_LEVELS = {"INFO": logging.INFO, "DEBUG": logging.DEBUG}

Expand Down Expand Up @@ -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)
Expand All @@ -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

Expand Down
2 changes: 1 addition & 1 deletion software/docs/fluidics-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions software/squid/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
40 changes: 37 additions & 3 deletions software/tests/control/core/fluidics_protocol/test_runner.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down
Loading