log: route task/component status output through logging, not print()

AttributeChange (the common base of every ATask and component ABC) now
sets self.log = logging.getLogger(type(self).__name__), so components
no longer need to hand-type their own name into each message. Wired
logging.basicConfig() in server/brewpi.py with a bare "%(name)s:
%(message)s" formatter - Tee (see prior commit) still supplies the
"<date>T<time>:" prefix, so lines read "<date>T<time>:<component>:
<message>" without double-stamping, and third-party loggers
(websockets, asyncio) now get the same formatting for free.

Converted the print() call sites that were standing in for this in
tasks/ and components/ (leaving __main__ demo blocks and explicit
debug-dump helpers alone).
This commit is contained in:
2026-07-10 22:00:04 +02:00
parent 6c746c8964
commit a1864a5257
12 changed files with 64 additions and 45 deletions
+3 -3
View File
@@ -45,7 +45,7 @@ class HeaterHendi(AHeater):
# tick loop (with self.device.open(): activate(True)/(False)) and
# from a client's Connect/Disconnect command, neither of which
# expect activate() itself to ever raise.
print(f"HeaterHendi: comm error in activate({enable}): {e}")
self.log.error(f"comm error in activate({enable}): {e}")
self.disconnect()
def is_activated(self):
@@ -55,7 +55,7 @@ class HeaterHendi(AHeater):
s = self.hendi.isRemoteEnable()
return '1' in s
except Exception as e:
print(f"HeaterHendi: comm error in is_activated: {e}")
self.log.error(f"comm error in is_activated: {e}")
self.disconnect()
return False
@@ -72,7 +72,7 @@ class HeaterHendi(AHeater):
self.hendi.setPowerWatts(power)
self.power_eff = self.hendi.getPowerWatts() if power > 0 else 0
except Exception as e:
print(f"HeaterHendi: comm error in process: {e}")
self.log.error(f"comm error in process: {e}")
self.disconnect()
self.power_eff = 0
+8 -6
View File
@@ -1,5 +1,6 @@
#!/usr/bin/python3
import logging
import time
import serial
import sys
@@ -11,6 +12,7 @@ class HendiException(Exception):
class HendiCtrl:
def __init__(self, port, speed, debug=False):
self.log = logging.getLogger(type(self).__name__)
self.debug = debug
self.prompt = b':'
self.sw_id = None
@@ -48,7 +50,7 @@ class HendiCtrl:
try:
self.ser.open()
except serial.SerialException as e:
print(f"HendiCtrl: connect failed: {e}")
self.log.error(f"connect failed: {e}")
return False
# The port itself is what "connected" means - a failed version query
# (e.g. the device sitting in its ungraceful-disconnect lockout, see
@@ -57,9 +59,9 @@ class HendiCtrl:
try:
self.sw_id = self.getSoftwareIdentifier()
self.sw_ver = self.getSoftwareVersion()
print(f"{self.sw_id}, F/W-Version: {self.sw_ver}")
self.log.info(f"{self.sw_id}, F/W-Version: {self.sw_ver}")
except HendiException:
print("HendiCtrl: Hendi not found")
self.log.warning("Hendi not found")
return True
@contextmanager
@@ -91,7 +93,7 @@ class HendiCtrl:
self.ser.rts = True
def firmware_update(self, filename):
print("Start firmware update")
self.log.info("Start firmware update")
self.enter_bootloader()
self.ser.readline()
@@ -122,7 +124,7 @@ class HendiCtrl:
self.ser.flushInput()
data = s.encode()
if self.debug:
print(f"HendiCtrl: -> {data!r}")
self.log.debug(f"-> {data!r}")
self.ser.write(data + b'\r')
def __read(self):
@@ -132,7 +134,7 @@ class HendiCtrl:
# Read answer line
answer_raw = self.ser.readline()
if self.debug:
print(f"HendiCtrl: <- echo={echo!r} answer={answer_raw!r}")
self.log.debug(f"<- echo={echo!r} answer={answer_raw!r}")
answer = answer_raw.decode('utf-8').replace('\r', '').replace('\n', '')
if ':' in answer:
result = answer.split(':')
+6 -4
View File
@@ -1,3 +1,4 @@
import logging
import time
import serial
import enum
@@ -68,6 +69,7 @@ class StatusError(enum.IntFlag):
class Pololu1376:
def __init__(self, serial_port):
self.log = logging.getLogger(type(self).__name__)
# Deferred-open pyserial idiom: serial_port is constructed with no
# port set (see components/actor/stirrerpololu1376.py), so it isn't
# actually opened until connect() is called - a missing/unplugged
@@ -88,7 +90,7 @@ class Pololu1376:
self.ser.close()
self.ser.open()
except serial.SerialException as e:
print(f"Pololu1376: connect failed: {e}")
self.log.error(f"connect failed: {e}")
return False
# set_output_flow_control() requires the port to already be open -
# can only happen here, after open() above, not at construction time.
@@ -96,10 +98,10 @@ class Pololu1376:
try:
self.stop()
self.firmware_version = self.get_firmware_version()
print("Pololu1376 F/W-Version:", self.firmware_version)
self.log.info("F/W-Version: {}".format(self.firmware_version))
return True
except Exception as e:
print(f"Pololu1376: connect failed: {e}")
self.log.error(f"connect failed: {e}")
self.ser.close()
self.firmware_version = None
return False
@@ -142,7 +144,7 @@ class Pololu1376:
rsp = self.cmd("GO")
errors = self.get_status_errors()
if errors:
print(f"Pololu1376: ERROR - still in fail-safe after GO, active errors: {errors!r}")
self.log.error(f"still in fail-safe after GO, active errors: {errors!r}")
return rsp
def stop(self):
+7 -7
View File
@@ -46,7 +46,7 @@ class StirrerPololu1376(AStirrer):
if not self.connected:
return
try:
print("activate {}".format(enable))
self.log.debug("activate {}".format(enable))
if enable:
self.drv.go()
else:
@@ -58,7 +58,7 @@ class StirrerPololu1376(AStirrer):
# loop (with self.device.open(): activate(True)/(False)) and
# from a client's Connect/Disconnect command, neither of which
# expect activate() itself to ever raise.
print(f"StirrerPololu1376: comm error in activate({enable}): {e}")
self.log.error(f"comm error in activate({enable}): {e}")
self.disconnect()
def _on_set_speed(self, speed):
@@ -66,9 +66,9 @@ class StirrerPololu1376(AStirrer):
return
try:
self.drv.motor_forward(speed)
print("Set speed to {} %".format(speed))
self.log.debug("Set speed to {} %".format(speed))
except Exception as e:
print(f"StirrerPololu1376: comm error in _on_set_speed: {e}")
self.log.error(f"comm error in _on_set_speed: {e}")
self.disconnect()
def _on_process(self):
@@ -77,12 +77,12 @@ class StirrerPololu1376(AStirrer):
try:
errors = self.drv.get_status_errors()
if errors:
print(f"StirrerPololu1376: motor controller reports errors: {errors!r}")
self.log.warning(f"motor controller reports errors: {errors!r}")
if StatusError.SAFE_START_VIOLATION in errors:
print("Recover after safe start violation!")
self.log.warning("Recover after safe start violation!")
self.drv.go()
except Exception as e:
print(f"StirrerPololu1376: comm error in _on_process: {e}")
self.log.error(f"comm error in _on_process: {e}")
self.disconnect()
+3 -3
View File
@@ -25,7 +25,7 @@ class TempSensor_max31865(ATemperatureSensor):
# temperature()'s own except handler already retries via
# reopen() on the next tick, same recovery path as a later
# runtime failure.
print(f"TempSensor_max31865: could not open SPI at startup: {e}")
self.log.error(f"could not open SPI at startup: {e}")
def _open_spi(self):
self.spi.open(0, 0)
@@ -56,7 +56,7 @@ class TempSensor_max31865(ATemperatureSensor):
try:
self._open_spi()
except Exception as e:
print(f"TempSensor_max31865: reopen failed: {e}")
self.log.error(f"reopen failed: {e}")
def read_reg(self, addr):
reg = self.spi.xfer([addr, 0xFF])
@@ -98,7 +98,7 @@ class TempSensor_max31865(ATemperatureSensor):
# nothing restarts a dead ATask). reopen() gives the SPI bus a
# chance to recover from a wedged state without a full process/
# Pi reboot - see docs/pi_deployment_notes.md.
print(f"TempSensor_max31865: comm error reading sensor, reopening SPI: {e}")
self.log.error(f"comm error reading sensor, reopening SPI: {e}")
self.reopen()
return self.temp
+22 -14
View File
@@ -2,6 +2,7 @@
import asyncio
import functools
import json
import logging
import os
import signal
import sys
@@ -20,20 +21,23 @@ from tasks import TaskManager, TempSensorTask, HeaterTask, PotTask, TcTask, Stir
import argparse as ap
log = logging.getLogger('brewpi')
class Tee:
"""Duplicates writes to multiple streams - used to mirror stdout/stderr
(everything the rest of the codebase already reaches via print()) into
a log file under logs/ as well as the console, without having to touch
every print() call site.
into a log file under logs/ as well as the console, without every
writer needing to know about either.
Also stamps every line with a "<date>T<time>:" prefix (existing print()
call sites already start their message with "Component: ..." - see e.g.
tasks/stirrer.py - so the combined line reads
"<date>T<time>:<component>: <message>"), so log entries can be
correlated with the JSON sample logs (ServerLogTask/SudLogTask) without
relying on journalctl's own timestamps, which aren't present in the
mirrored log files themselves."""
Also stamps every line with a "<date>T<time>:" prefix. Every task/
component logs via logging (see utils/value.py's AttributeChange, which
gives self.log to all of them), configured below with a bare
"%(name)s:%(message)s" formatter - Tee supplies the timestamp instead,
so the combined line reads "<date>T<time>:<component>:<message>" (see
logging.basicConfig() call below) without double-stamping. This lets
log entries be correlated with the JSON sample logs (ServerLogTask/
SudLogTask) without relying on journalctl's own timestamps, which
aren't present in the mirrored log files themselves."""
def __init__(self, *streams):
self.streams = streams
@@ -92,7 +96,11 @@ if __name__ == '__main__':
latest_log_file = open(latest_log_path, "w", buffering=1)
sys.stdout = Tee(sys.stdout, log_file, latest_log_file)
sys.stderr = Tee(sys.stderr, log_file, latest_log_file)
print("Logging to {}".format(log_path))
# No "%(asctime)s" here - Tee (above) already stamps every mirrored
# line with "<date>T<time>:", so this only contributes the
# "<component>:<message>" part (see Tee's own docstring).
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(name)s:%(message)s')
log.info("Logging to {}".format(log_path))
config = json.load(open(args.config))
dispatcher = MessageDispatcher()
@@ -246,7 +254,7 @@ if __name__ == '__main__':
http_handler = functools.partial(SimpleHTTPRequestHandler, directory=web_dir)
http_server = ThreadingHTTPServer(("0.0.0.0", args.http_port), http_handler)
threading.Thread(target=http_server.serve_forever, daemon=True).start()
print("Serving {} on http://0.0.0.0:{}".format(web_dir, args.http_port))
log.info("Serving {} on http://0.0.0.0:{}".format(web_dir, args.http_port))
# systemd's `stop`/`restart` send SIGTERM, whose default disposition is to
# kill the process immediately - skipping the finally: block below
@@ -259,7 +267,7 @@ if __name__ == '__main__':
try:
loop.run_forever()
except KeyboardInterrupt:
print("\nShutting down...")
log.info("Shutting down...")
finally:
# Cancel all tasks so their finally blocks (e.g. HeaterTask's/
# StirrerTask's `with device.open()`) get a chance to run before we
@@ -278,4 +286,4 @@ if __name__ == '__main__':
stirrer.activate(False)
http_server.shutdown()
loop.close()
print("Server stopped.")
log.info("Server stopped.")
+2 -2
View File
@@ -178,11 +178,11 @@ class HeaterTask(ATask):
try:
self.device.process()
except Exception as e:
print(f"HeaterTask: comm error, marking disconnected: {e}")
self.log.error(f"comm error, marking disconnected: {e}")
self.disconnect()
await asyncio.sleep(self.interval)
except Exception as e:
print(f"HeaterTask: unexpected error, recovering: {e}")
self.log.error(f"unexpected error, recovering: {e}")
try:
self.disconnect()
except Exception:
+1 -1
View File
@@ -143,4 +143,4 @@ class ServerLogTask(ATask):
for name in (filename, self._latest_filename()):
with open(os.path.join(self.path, name), 'w') as f:
json.dump(log_data, f, indent='\t')
print('Server log: wrote {} samples to {}'.format(len(self._samples), filename))
self.log.info('Wrote {} samples to {}'.format(len(self._samples), filename))
+2 -2
View File
@@ -88,11 +88,11 @@ class StirrerTask(ATask):
try:
self.device.process()
except Exception as e:
print(f"StirrerTask: comm error, marking disconnected: {e}")
self.log.error(f"comm error, marking disconnected: {e}")
self.disconnect()
await asyncio.sleep(self.interval)
except Exception as e:
print(f"StirrerTask: unexpected error, recovering: {e}")
self.log.error(f"unexpected error, recovering: {e}")
try:
self.disconnect()
except Exception:
+1 -1
View File
@@ -634,7 +634,7 @@ class SudTask(ATask):
await self.msg_handler.send(data)
async def on_process(self):
print("{}: Started with interval {} s".format(self.msg_handler.get_key(), self.interval))
self.log.info("Started with interval {} s".format(self.interval))
self.sud.set_on_changed('step', self.on_step_changed)
self.sud.set_on_changed('state', self.on_state_changed)
+2 -2
View File
@@ -24,7 +24,7 @@ class TempSensorTask(ATask):
try:
self.sensor.temperature()
except Exception as e:
print(f"TempSensorTask: comm error priming sensor: {e}")
self.log.error(f"comm error priming sensor: {e}")
self.sensor.set_on_changed("temp", ChangedFloat(self.on_temp_changed, prec=1).set)
def on_temp_changed(self, value):
@@ -44,5 +44,5 @@ class TempSensorTask(ATask):
try:
self.sensor.temperature()
except Exception as e:
print(f"TempSensorTask: comm error reading sensor: {e}")
self.log.error(f"comm error reading sensor: {e}")
await asyncio.sleep(self.interval)
+7
View File
@@ -1,3 +1,4 @@
import logging
class Value:
@@ -53,6 +54,12 @@ class ChangedInteger(object):
class AttributeChange(object):
def __init__(self):
self.callbacks = {}
# Common ancestor of every task (tasks/task.py's ATask) and component
# (Connectable/APid/APlant/ATemperatureSensor) - giving it a logger
# here makes self.log available everywhere via one change, named
# after the concrete subclass so log lines self-identify their
# component without each call site typing it out.
self.log = logging.getLogger(type(self).__name__)
def set_on_changed(self, key, on_changed):
if key not in self.callbacks: