Skip to content

Commit 3e5dc60

Browse files
committed
misc: Optimize logging statements memory usage.
1 parent 37f7644 commit 3e5dc60

File tree

2 files changed

+41
-22
lines changed

2 files changed

+41
-22
lines changed

src/arduino_iot_cloud/ucloud.py

Lines changed: 38 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ def timestamp():
3535
return int(time.time())
3636

3737

38+
def log_enabled(level):
39+
return logging.getLogger().isEnabledFor(level)
40+
41+
3842
class ArduinoCloudObject(SenmlRecord):
3943
def __init__(self, name, **kwargs):
4044
self.on_read = kwargs.pop("on_read", None)
@@ -97,10 +101,11 @@ def value(self, value):
97101
)
98102
self._updated = True
99103
self.timestamp = timestamp()
100-
logging.debug(
101-
f"%s: {self.name} value: {value} ts: {self.timestamp}"
102-
% ("Init" if self.value is None else "Update")
103-
)
104+
if log_enabled(logging.DEBUG):
105+
logging.debug(
106+
f"%s: {self.name} value: {value} ts: {self.timestamp}"
107+
% ("Init" if self.value is None else "Update")
108+
)
104109
self._value = value
105110

106111
def __getattr__(self, attr):
@@ -181,7 +186,8 @@ def __init__(
181186
# Use M2Crypto to load key and cert from HSM.
182187
import M2Crypto # noqa
183188
except (ImportError, AttributeError):
184-
logging.error("The m2crypto module is required to use HSM.")
189+
if log_enabled(logging.ERROR):
190+
logging.error("The m2crypto module is required to use HSM.")
185191
sys.exit(1)
186192

187193
# Convert args to bytes if they are passed as strings.
@@ -235,18 +241,21 @@ def update_systime(self, server, timeout):
235241
ntptime.host = server
236242
ntptime.timeout = timeout
237243
ntptime.settime()
238-
logging.info("RTC time set from NTP.")
244+
if log_enabled(logging.INFO):
245+
logging.info("RTC time set from NTP.")
239246
except ImportError:
240247
pass # No ntptime module.
241248
except Exception as e:
242-
logging.error(f"Failed to set RTC time from NTP: {e}.")
249+
if log_enabled(logging.ERROR):
250+
logging.error(f"Failed to set RTC time from NTP: {e}.")
243251

244252
def create_task(self, name, coro, *args, **kwargs):
245253
if callable(coro):
246254
coro = coro(*args)
247255
if self.started:
248256
self.tasks[name] = asyncio.create_task(coro)
249-
logging.info(f"task: {name} created.")
257+
if log_enabled(logging.INFO):
258+
logging.info(f"task: {name} created.")
250259
else:
251260
# Defer task creation until there's a running event loop.
252261
self.tasks[name] = coro
@@ -275,12 +284,15 @@ def senml_generic_callback(self, record, **kwargs):
275284
# This callback catches all unknown/umatched sub/records that were not part of the pack.
276285
rname, sname = record.name.split(":") if ":" in record.name else [record.name, None]
277286
if rname in self.records:
278-
logging.info(f"Ignoring cloud initialization for record: {record.name}")
287+
if log_enabled(logging.INFO):
288+
logging.info(f"Ignoring cloud initialization for record: {record.name}")
279289
else:
280-
logging.warning(f"Unkown record found: {record.name} value: {record.value}")
290+
if log_enabled(logging.WARNING):
291+
logging.warning(f"Unkown record found: {record.name} value: {record.value}")
281292

282293
def mqtt_callback(self, topic, message):
283-
logging.debug(f"mqtt topic: {topic[-8:]}... message: {message[:8]}...")
294+
if log_enabled(logging.DEBUG):
295+
logging.debug(f"mqtt topic: {topic[-8:]}... message: {message[:8]}...")
284296
self.senmlpack.clear()
285297
for record in self.records.values():
286298
# If the object is uninitialized, updates are always allowed even if it's a read-only
@@ -307,18 +319,22 @@ async def discovery_task(self, interval=0.100):
307319
lastval_record.add_to_pack(self.senmlpack)
308320
self.mqtt.subscribe(self.create_topic("shadow", "i"), qos=1)
309321
self.mqtt.publish(self.create_topic("shadow", "o"), self.senmlpack.to_cbor(), qos=1)
310-
logging.info("Device configured via discovery protocol.")
322+
323+
if log_enabled(logging.INFO):
324+
logging.info("Device configured via discovery protocol.")
311325
await asyncio.sleep(interval)
312326
raise DoneException()
313327

314328
async def conn_task(self, interval=1.0, backoff=1.2):
315-
logging.info("Connecting to Arduino IoT cloud...")
329+
if log_enabled(logging.INFO):
330+
logging.info("Connecting to Arduino IoT cloud...")
316331
while True:
317332
try:
318333
self.mqtt.connect()
319334
break
320335
except Exception as e:
321-
logging.warning(f"Connection failed {e}, retrying after {interval}s")
336+
if log_enabled(logging.WARNING):
337+
logging.warning(f"Connection failed {e}, retrying after {interval}s")
322338
await asyncio.sleep(interval)
323339
interval = min(interval * backoff, 4.0)
324340

@@ -338,15 +354,17 @@ async def mqtt_task(self, interval=0.100):
338354
if record.updated:
339355
record.add_to_pack(self.senmlpack, push=True)
340356
if len(self.senmlpack._data):
341-
logging.debug("Pushing records to Arduino IoT cloud:")
342-
for record in self.senmlpack._data:
343-
logging.debug(f" ==> record: {record.name} value: {str(record.value)[:48]}...")
357+
if log_enabled(logging.DEBUG):
358+
logging.debug("Pushing records to Arduino IoT cloud:")
359+
for record in self.senmlpack._data:
360+
logging.debug(f" ==> record: {record.name} value: {str(record.value)[:48]}...")
344361
self.mqtt.publish(self.topic_out, self.senmlpack.to_cbor(), qos=1)
345362
self.last_ping = timestamp()
346363
elif self.keepalive and (timestamp() - self.last_ping) > self.keepalive:
347364
self.mqtt.ping()
348365
self.last_ping = timestamp()
349-
logging.debug("No records to push, sent a ping request.")
366+
if log_enabled(logging.DEBUG):
367+
logging.debug("No records to push, sent a ping request.")
350368
await asyncio.sleep(interval)
351369
raise DoneException()
352370

@@ -375,9 +393,9 @@ async def run(self):
375393
if task.done():
376394
self.tasks.pop(name)
377395
self.records.pop(name, None)
378-
if isinstance(task_except, DoneException):
396+
if isinstance(task_except, DoneException) and log_enabled(logging.INFO):
379397
logging.info(f"task: {name} complete.")
380-
elif task_except is not None:
398+
elif task_except is not None and log_enabled(logging.ERROR):
381399
logging.error(f"task: {name} raised exception: {str(task_except)}.")
382400
if name == "mqtt_task":
383401
self.create_task("conn_task", self.conn_task)

src/arduino_iot_cloud/umqtt.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,8 @@ def publish(self, topic, msg, retain=False, qos=0):
186186
assert 0
187187

188188
def subscribe(self, topic, qos=0):
189-
logging.info(f"Subscribe: {topic}.")
189+
if logging.getLogger().isEnabledFor(logging.INFO):
190+
logging.info(f"Subscribe: {topic}.")
190191
assert self.cb is not None, "Subscribe callback is not set"
191192
pkt = bytearray(b"\x82\0\0\0")
192193
self.pid += 1
@@ -243,5 +244,5 @@ def wait_msg(self):
243244
# the same processing as wait_msg.
244245
def check_msg(self):
245246
r, w, e = select.select([self.sock], [], [], 0.05)
246-
if (len(r)):
247+
if len(r):
247248
return self.wait_msg()

0 commit comments

Comments
 (0)