Skip to content

Commit c97f9a2

Browse files
committed
F-string logging
Un petit gain d'efficacité tant qu'à y être
1 parent 584dd33 commit c97f9a2

File tree

4 files changed

+22
-20
lines changed

4 files changed

+22
-20
lines changed

pyhilo/api.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ async def _async_request(
291291
try:
292292
data = await resp.json(content_type=None)
293293
except json.decoder.JSONDecodeError:
294-
LOG.warning(f"JSON Decode error: {resp.__dict__}")
294+
LOG.warning("JSON Decode error: %s", resp.__dict__)
295295
message = await resp.text()
296296
data = {"error": message}
297297
else:
@@ -353,15 +353,15 @@ async def _async_handle_on_backoff(self, _: dict[str, Any]) -> None:
353353
err: ClientResponseError = err_info[1].with_traceback(err_info[2]) # type: ignore
354354

355355
if err.status in (401, 403):
356-
LOG.warning(f"Refreshing websocket token {err.request_info.url}")
356+
LOG.warning("Refreshing websocket token %s", err.request_info.url)
357357
if (
358358
"client/negotiate" in str(err.request_info.url)
359359
and err.request_info.method == "POST"
360360
):
361361
LOG.info(
362362
"401 detected on websocket, refreshing websocket token. Old url: {self.ws_url} Old Token: {self.ws_token}"
363363
)
364-
LOG.info(f"401 detected on {err.request_info.url}")
364+
LOG.info("401 detected on %s", err.request_info.url)
365365
async with self._backoff_refresh_lock_ws:
366366
await self.refresh_ws_token()
367367
await self.get_websocket_params()
@@ -480,7 +480,7 @@ async def fb_install(self, fb_id: str) -> None:
480480
json=body,
481481
)
482482
except ClientResponseError as err:
483-
LOG.error(f"ClientResponseError: {err}")
483+
LOG.error("ClientResponseError: %s", err)
484484
if err.status in (401, 403):
485485
raise InvalidCredentialsError("Invalid credentials") from err
486486
raise RequestError(err) from err
@@ -518,14 +518,14 @@ async def android_register(self) -> None:
518518
data=parsed_body,
519519
)
520520
except ClientResponseError as err:
521-
LOG.error(f"ClientResponseError: {err}")
521+
LOG.error("ClientResponseError: %s", err)
522522
if err.status in (401, 403):
523523
raise InvalidCredentialsError("Invalid credentials") from err
524524
raise RequestError(err) from err
525525
LOG.debug("Android client register: %s", resp)
526526
msg: str = resp.get("message", "")
527527
if msg.startswith("Error="):
528-
LOG.error(f"Android registration error: {msg}")
528+
LOG.error("Android registration error: %s", msg)
529529
raise RequestError
530530
token = msg.split("=")[-1]
531531
LOG.debug("Calling set_state android_register")

pyhilo/device/__init__.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def __init__(
5151
def update(self, **kwargs: Dict[str, Union[str, int, Dict]]) -> None:
5252
# TODO(dvd): This has to be re-written, this is not dynamic at all.
5353
if self._api.log_traces:
54-
LOG.debug(f"[TRACE] Adding device {kwargs}")
54+
LOG.debug("[TRACE] Adding device %s", kwargs)
5555
for orig_att, val in kwargs.items():
5656
att = camel_to_snake(orig_att)
5757
if reading_att := HILO_READING_TYPES.get(orig_att):
@@ -70,7 +70,7 @@ def update(self, **kwargs: Dict[str, Union[str, int, Dict]]) -> None:
7070
self.update_readings(DeviceReading(**reading)) # type: ignore
7171

7272
if att not in HILO_DEVICE_ATTRIBUTES:
73-
LOG.warning(f"Unknown device attribute {att}: {val}")
73+
LOG.warning("Unknown device attribute %s: %s", att, val)
7474
continue
7575
elif att in HILO_LIST_ATTRIBUTES:
7676
# This is where we generated the supported_attributes and settable_attributes
@@ -108,7 +108,7 @@ def update(self, **kwargs: Dict[str, Union[str, int, Dict]]) -> None:
108108

109109
async def set_attribute(self, attribute: str, value: Union[str, int, None]) -> None:
110110
if dev_attribute := cast(DeviceAttribute, self._api.dev_atts(attribute)):
111-
LOG.debug(f"{self._tag} Setting {dev_attribute} to {value}")
111+
LOG.debug("%s Setting %s to %s", self._tag, dev_attribute, value)
112112
await self._set_attribute(dev_attribute, value)
113113
return
114114
LOG.warning(
@@ -134,7 +134,7 @@ async def _set_attribute(
134134
)
135135
)
136136
else:
137-
LOG.warning(f"{self._tag} Invalid attribute {attribute} for device")
137+
LOG.warning("%s Invalid attribute %s for device", self._tag, attribute)
138138

139139
def get_attribute(self, attribute: str) -> Union[DeviceReading, None]:
140140
if dev_attribute := cast(DeviceAttribute, self._api.dev_atts(attribute)):
@@ -245,7 +245,7 @@ def __init__(self, **kwargs: Dict[str, Any]):
245245
else ""
246246
)
247247
if not self.device_attribute:
248-
LOG.warning(f"Received invalid reading for {self.device_id}: {kwargs}")
248+
LOG.warning("Received invalid reading for %s: %s", self.device_id, kwargs)
249249

250250
def __repr__(self) -> str:
251251
return f"<Reading {self.device_attribute.attr} {self.value}{self.unit_of_measurement}>"

pyhilo/devices.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def generate_device(self, device: dict) -> HiloDevice:
8787
try:
8888
device_type = HILO_DEVICE_TYPES[dev.type]
8989
except KeyError:
90-
LOG.warning(f"Unknown device type {dev.type}, adding as Sensor")
90+
LOG.warning("Unknown device type %s, adding as Sensor", dev.type)
9191
device_type = "Sensor"
9292
dev.__class__ = globals()[device_type]
9393
return dev

pyhilo/websocket.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,9 @@ async def _async_receive_json(self) -> list[Dict[str, Any]]:
173173
response = await self._client.receive(300)
174174

175175
if response.type in (WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING):
176-
LOG.error(f"Websocket: Received event to close connection: {response.type}")
176+
LOG.error(
177+
"Websocket: Received event to close connection: %s", response.type
178+
)
177179
raise ConnectionClosedError("Connection was closed.")
178180

179181
if response.type == WSMsgType.ERROR:
@@ -183,7 +185,7 @@ async def _async_receive_json(self) -> list[Dict[str, Any]]:
183185
raise ConnectionFailedError
184186

185187
if response.type != WSMsgType.TEXT:
186-
LOG.error(f"Websocket: Received invalid message: {response}")
188+
LOG.error("Websocket: Received invalid message: %s", response)
187189
raise InvalidMessageError(f"Received non-text message: {response.type}")
188190

189191
messages: list[Dict[str, Any]] = []
@@ -196,7 +198,7 @@ async def _async_receive_json(self) -> list[Dict[str, Any]]:
196198
except ValueError as v_exc:
197199
raise InvalidMessageError("Received invalid JSON") from v_exc
198200
except json.decoder.JSONDecodeError as j_exc:
199-
LOG.error(f"Received invalid JSON: {msg}")
201+
LOG.error("Received invalid JSON: %s", msg)
200202
LOG.exception(j_exc)
201203
data = {}
202204

@@ -307,14 +309,14 @@ async def async_connect(self) -> None:
307309
**proxy_env,
308310
)
309311
except (ClientError, ServerDisconnectedError, WSServerHandshakeError) as err:
310-
LOG.error(f"Unable to connect to WS server {err}")
312+
LOG.error("Unable to connect to WS server %s", err)
311313
if hasattr(err, "status") and err.status in (401, 403, 404, 409):
312314
raise InvalidCredentialsError("Invalid credentials") from err
313315
except Exception as err:
314-
LOG.error(f"Unable to connect to WS server {err}")
316+
LOG.error("Unable to connect to WS server %s", err)
315317
raise CannotConnectError(err) from err
316318

317-
LOG.info(f"Connected to websocket server {self._api.endpoint}")
319+
LOG.info("Connected to websocket server %s", self._api.endpoint)
318320

319321
# Quick pause to prevent race condition
320322
await asyncio.sleep(0.05)
@@ -353,11 +355,11 @@ async def async_listen(self) -> None:
353355
LOG.info("Websocket: Listen cancelled.")
354356
raise
355357
except ConnectionClosedError as err:
356-
LOG.error(f"Websocket: Closed while listening: {err}")
358+
LOG.error("Websocket: Closed while listening: %s", err)
357359
LOG.exception(err)
358360
pass
359361
except InvalidMessageError as err:
360-
LOG.warning(f"Websocket: Received invalid json : {err}")
362+
LOG.warning("Websocket: Received invalid json : %s", err)
361363
pass
362364
finally:
363365
LOG.info("Websocket: Listen completed; cleaning up")

0 commit comments

Comments
 (0)