Skip to content

Commit 4ed9b7e

Browse files
authored
[Python] Adjust logging levels in Python controller (#34346)
Use global loggers per-module which is more Pythonic and avoids unnecessary logger instances. Also use the module name as the logger name consistently. Avoid using the warning level for messages which are really only informational. Also lower the log level of storage messages to debug, as they are really not that important. Drop some unnecessary logs like on every storage commit.
1 parent 2affb95 commit 4ed9b7e

File tree

5 files changed

+50
-51
lines changed

5 files changed

+50
-51
lines changed

src/controller/python/chip/CertificateAuthority.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
from chip.native import PyChipError
2929
from chip.storage import PersistentStorage
3030

31+
LOGGER = logging.getLogger(__name__)
32+
3133

3234
class CertificateAuthority:
3335
''' This represents an operational Root Certificate Authority (CA) with a root key key pair with associated
@@ -64,7 +66,7 @@ def __init__(self, chipStack: ChipStack.ChipStack, caIndex: int, persistentStora
6466
persistentStorage: An optional reference to a PersistentStorage object. If one is provided, it will pick that over
6567
the default PersistentStorage object retrieved from the chipStack.
6668
'''
67-
self.logger().warning(f"New CertificateAuthority at index {caIndex}")
69+
LOGGER.info(f"New CertificateAuthority at index {caIndex}")
6870

6971
self._chipStack = chipStack
7072
self._caIndex = caIndex
@@ -105,7 +107,7 @@ def LoadFabricAdminsFromStorage(self):
105107
if (not (self._isActive)):
106108
raise RuntimeError("Object isn't active")
107109

108-
self.logger().warning("Loading fabric admins from storage...")
110+
LOGGER.info("Loading fabric admins from storage...")
109111

110112
caList = self._persistentStorage.GetReplKey(key='caList')
111113
if (str(self._caIndex) not in caList):
@@ -244,7 +246,7 @@ def LoadAuthoritiesFromStorage(self):
244246
if (not (self._isActive)):
245247
raise RuntimeError("Object is not active")
246248

247-
self.logger().warning("Loading certificate authorities from storage...")
249+
LOGGER.info("Loading certificate authorities from storage...")
248250

249251
#
250252
# Persist details to storage (read modify write).

src/controller/python/chip/ChipDeviceCtrl.py

+17-16
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@
6161
# Defined in $CHIP_ROOT/src/lib/core/CHIPError.h
6262
CHIP_ERROR_TIMEOUT: int = 50
6363

64+
LOGGER = logging.getLogger(__name__)
65+
6466
_DevicePairingDelegate_OnPairingCompleteFunct = CFUNCTYPE(None, PyChipError)
6567
_DeviceUnpairingCompleteFunct = CFUNCTYPE(None, c_uint64, PyChipError)
6668
_DevicePairingDelegate_OnCommissioningCompleteFunct = CFUNCTYPE(
@@ -401,17 +403,17 @@ def __init__(self, name: str = ''):
401403
def _set_dev_ctrl(self, devCtrl, pairingDelegate):
402404
def HandleCommissioningComplete(nodeId: int, err: PyChipError):
403405
if err.is_success:
404-
logging.info("Commissioning complete")
406+
LOGGER.info("Commissioning complete")
405407
else:
406-
logging.warning("Failed to commission: {}".format(err))
408+
LOGGER.warning("Failed to commission: {}".format(err))
407409

408410
self._dmLib.pychip_DeviceController_SetIcdRegistrationParameters(False, None)
409411

410412
if self._dmLib.pychip_TestCommissionerUsed():
411413
err = self._dmLib.pychip_GetCompletionError()
412414

413415
if self._commissioning_context.future is None:
414-
logging.exception("HandleCommissioningComplete called unexpectedly")
416+
LOGGER.exception("HandleCommissioningComplete called unexpectedly")
415417
return
416418

417419
if err.is_success:
@@ -425,14 +427,14 @@ def HandleFabricCheck(nodeId):
425427
def HandleOpenWindowComplete(nodeid: int, setupPinCode: int, setupManualCode: str,
426428
setupQRCode: str, err: PyChipError) -> None:
427429
if err.is_success:
428-
logging.info("Open Commissioning Window complete setting nodeid {} pincode to {}".format(nodeid, setupPinCode))
430+
LOGGER.info("Open Commissioning Window complete setting nodeid {} pincode to {}".format(nodeid, setupPinCode))
429431
commissioningParameters = CommissioningParameters(
430432
setupPinCode=setupPinCode, setupManualCode=setupManualCode.decode(), setupQRCode=setupQRCode.decode())
431433
else:
432-
logging.warning("Failed to open commissioning window: {}".format(err))
434+
LOGGER.warning("Failed to open commissioning window: {}".format(err))
433435

434436
if self._open_window_context.future is None:
435-
logging.exception("HandleOpenWindowComplete called unexpectedly")
437+
LOGGER.exception("HandleOpenWindowComplete called unexpectedly")
436438
return
437439

438440
if err.is_success:
@@ -442,12 +444,12 @@ def HandleOpenWindowComplete(nodeid: int, setupPinCode: int, setupManualCode: st
442444

443445
def HandleUnpairDeviceComplete(nodeid: int, err: PyChipError):
444446
if err.is_success:
445-
logging.info("Succesfully unpaired device with nodeid {}".format(nodeid))
447+
LOGGER.info("Succesfully unpaired device with nodeid {}".format(nodeid))
446448
else:
447-
logging.warning("Failed to unpair device: {}".format(err))
449+
LOGGER.warning("Failed to unpair device: {}".format(err))
448450

449451
if self._unpair_device_context.future is None:
450-
logging.exception("HandleUnpairDeviceComplete called unexpectedly")
452+
LOGGER.exception("HandleUnpairDeviceComplete called unexpectedly")
451453
return
452454

453455
if err.is_success:
@@ -457,9 +459,9 @@ def HandleUnpairDeviceComplete(nodeid: int, err: PyChipError):
457459

458460
def HandlePASEEstablishmentComplete(err: PyChipError):
459461
if not err.is_success:
460-
logging.warning("Failed to establish secure session to device: {}".format(err))
462+
LOGGER.warning("Failed to establish secure session to device: {}".format(err))
461463
else:
462-
logging.info("Established secure session with Device")
464+
LOGGER.info("Established secure session with Device")
463465

464466
if self._commissioning_context.future is not None:
465467
# During Commissioning, HandlePASEEstablishmentComplete will also be called.
@@ -469,7 +471,7 @@ def HandlePASEEstablishmentComplete(err: PyChipError):
469471
return
470472

471473
if self._pase_establishment_context.future is None:
472-
logging.exception("HandlePASEEstablishmentComplete called unexpectedly")
474+
LOGGER.exception("HandlePASEEstablishmentComplete called unexpectedly")
473475
return
474476

475477
if err.is_success:
@@ -926,7 +928,7 @@ def GetConnectedDeviceSync(self, nodeid, allowPASE=True, timeoutMs: int = None):
926928
res = self._ChipStack.Call(lambda: self._dmLib.pychip_GetDeviceBeingCommissioned(
927929
self.devCtrl, nodeid, byref(returnDevice)), timeoutMs)
928930
if res.is_success:
929-
logging.info('Using PASE connection')
931+
LOGGER.info('Using PASE connection')
930932
return DeviceProxyWrapper(returnDevice, DeviceProxyWrapper.DeviceProxyType.COMMISSIONEE, self._dmLib)
931933

932934
class DeviceAvailableClosure():
@@ -992,7 +994,7 @@ async def GetConnectedDevice(self, nodeid, allowPASE: bool = True, timeoutMs: in
992994
res = await self._ChipStack.CallAsync(lambda: self._dmLib.pychip_GetDeviceBeingCommissioned(
993995
self.devCtrl, nodeid, byref(returnDevice)), timeoutMs)
994996
if res.is_success:
995-
logging.info('Using PASE connection')
997+
LOGGER.info('Using PASE connection')
996998
return DeviceProxyWrapper(returnDevice, DeviceProxyWrapper.DeviceProxyType.COMMISSIONEE, self._dmLib)
997999

9981000
eventLoop = asyncio.get_running_loop()
@@ -1348,7 +1350,6 @@ def _parseEventPathTuple(self, pathTuple: typing.Union[
13481350
# Wildcard
13491351
return ClusterAttribute.EventPath()
13501352
elif not isinstance(pathTuple, tuple):
1351-
logging.debug(type(pathTuple))
13521353
if isinstance(pathTuple, int):
13531354
return ClusterAttribute.EventPath(EndpointId=pathTuple)
13541355
elif issubclass(pathTuple, ClusterObjects.Cluster):
@@ -2115,7 +2116,7 @@ async def CommissionIP(self, ipaddr: str, setupPinCode: int, nodeid: int) -> int
21152116

21162117
def NOCChainCallback(self, nocChain):
21172118
if self._issue_node_chain_context.future is None:
2118-
logging.exception("NOCChainCallback while not expecting a callback")
2119+
LOGGER.exception("NOCChainCallback while not expecting a callback")
21192120
return
21202121
self._issue_node_chain_context.future.set_result(nocChain)
21212122
return

src/controller/python/chip/FabricAdmin.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
from chip.crypto import p256keypair
2626
from chip.native import GetLibraryHandle
2727

28+
LOGGER = logging.getLogger(__name__)
29+
2830

2931
class FabricAdmin:
3032
''' Administers a fabric associated with a unique FabricID under a given CertificateAuthority
@@ -34,10 +36,6 @@ class FabricAdmin:
3436
def _Handle(cls):
3537
return GetLibraryHandle()
3638

37-
@classmethod
38-
def logger(cls):
39-
return logging.getLogger('FabricAdmin')
40-
4139
def __init__(self, certificateAuthority: CertificateAuthority.CertificateAuthority, vendorId: int, fabricId: int = 1):
4240
''' Initializes the object.
4341
@@ -60,7 +58,7 @@ def __init__(self, certificateAuthority: CertificateAuthority.CertificateAuthori
6058
self._fabricId = fabricId
6159
self._certificateAuthority = certificateAuthority
6260

63-
self.logger().warning(f"New FabricAdmin: FabricId: 0x{self._fabricId:016X}, VendorId = 0x{self.vendorId:04X}")
61+
LOGGER.info(f"New FabricAdmin: FabricId: 0x{self._fabricId:016X}, VendorId = 0x{self.vendorId:04X}")
6462

6563
self._isActive = True
6664
self._activeControllers = []
@@ -94,7 +92,7 @@ def NewController(self, nodeId: int = None, paaTrustStorePath: str = "",
9492
if (nodeId in nodeIdList):
9593
raise RuntimeError(f"Provided NodeId {nodeId} collides with an existing controller instance!")
9694

97-
self.logger().warning(
95+
LOGGER.info(
9896
f"Allocating new controller with CaIndex: {self._certificateAuthority.caIndex}, "
9997
f"FabricId: 0x{self._fabricId:016X}, NodeId: 0x{nodeId:016X}, CatTags: {catTags}")
10098

src/controller/python/chip/clusters/Attribute.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@
4040

4141
from .ClusterObjects import Cluster, ClusterAttributeDescriptor, ClusterEvent
4242

43+
LOGGER = logging.getLogger(__name__)
44+
4345

4446
@unique
4547
class EventTimestampType(Enum):
@@ -569,7 +571,7 @@ def subscriptionId(self) -> int:
569571

570572
def Shutdown(self):
571573
if (self._isDone):
572-
print("Subscription was already terminated previously!")
574+
LOGGER.warning("Subscription 0x%08x was already terminated previously!", self.subscriptionId)
573575
return
574576

575577
handle = chip.native.GetLibraryHandle()
@@ -675,7 +677,7 @@ def handleAttributeData(self, path: AttributePath, dataVersion: int, status: int
675677
self._changedPathSet.add(path)
676678

677679
except Exception as ex:
678-
logging.exception(ex)
680+
LOGGER.exception(ex)
679681

680682
def handleEventData(self, header: EventHeader, path: EventPath, data: bytes, status: int):
681683
try:
@@ -693,12 +695,12 @@ def handleEventData(self, header: EventHeader, path: EventPath, data: bytes, sta
693695
try:
694696
eventValue = eventType.FromTLV(data)
695697
except Exception as ex:
696-
logging.error(
698+
LOGGER.error(
697699
f"Error convering TLV to Cluster Object for path: Endpoint = {path.EndpointId}/"
698700
f"Cluster = {path.ClusterId}/Event = {path.EventId}")
699-
logging.error(
701+
LOGGER.error(
700702
f"Failed Cluster Object: {str(eventType)}")
701-
logging.error(ex)
703+
LOGGER.error(ex)
702704
eventValue = ValueDecodeFailure(
703705
tlvData, ex)
704706

@@ -715,7 +717,7 @@ def handleEventData(self, header: EventHeader, path: EventPath, data: bytes, sta
715717
eventResult, self._subscription_handler)
716718

717719
except Exception as ex:
718-
logging.exception(ex)
720+
LOGGER.exception(ex)
719721

720722
def handleError(self, chipError: PyChipError):
721723
self._resultError = chipError
@@ -726,7 +728,6 @@ def _handleSubscriptionEstablished(self, subscriptionId):
726728
self, subscriptionId, self._devCtrl)
727729
self._future.set_result(self._subscription_handler)
728730
else:
729-
logging.info("Re-subscription succeeded!")
730731
if self._subscription_handler._onResubscriptionSucceededCb is not None:
731732
if (self._subscription_handler._onResubscriptionSucceededCb_isAsync):
732733
self._event_loop.create_task(
@@ -761,7 +762,7 @@ def _handleReportEnd(self):
761762
attribute_path = TypedAttributePath(Path=change)
762763
except (KeyError, ValueError) as err:
763764
# path could not be resolved into a TypedAttributePath
764-
logging.getLogger(__name__).exception(err)
765+
LOGGER.exception(err)
765766
continue
766767
self._subscription_handler.OnAttributeChangeCb(
767768
attribute_path, self._subscription_handler)
@@ -816,7 +817,7 @@ def handleResponse(self, path: AttributePath, status: int):
816817
imStatus = chip.interaction_model.Status(status)
817818
self._resultData.append(AttributeWriteResult(Path=path, Status=imStatus))
818819
except ValueError as ex:
819-
logging.exception(ex)
820+
LOGGER.exception(ex)
820821

821822
def handleError(self, chipError: PyChipError):
822823
self._resultError = chipError

src/controller/python/chip/storage/__init__.py

+14-17
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929
import chip.exceptions
3030
import chip.native
3131

32+
LOGGER = logging.getLogger(__name__)
33+
3234
_SyncSetKeyValueCbFunct = CFUNCTYPE(
3335
None, py_object, c_char_p, POINTER(c_char), c_uint16)
3436
_SyncGetKeyValueCbFunct = CFUNCTYPE(
@@ -91,9 +93,6 @@ class PersistentStorage:
9193
9294
Object must be resident before the Matter stack starts up and last past its shutdown.
9395
'''
94-
@classmethod
95-
def logger(cls):
96-
return logging.getLogger('PersistentStorage')
9796

9897
def __init__(self, path: str = None, jsonData: Dict = None):
9998
''' Initializes the object with either a path to a JSON file that contains the configuration OR
@@ -109,9 +108,9 @@ def __init__(self, path: str = None, jsonData: Dict = None):
109108
raise ValueError("Can't provide both a valid path and jsonData")
110109

111110
if (path is not None):
112-
self.logger().warn(f"Initializing persistent storage from file: {path}")
111+
LOGGER.info(f"Initializing persistent storage from file: {path}")
113112
else:
114-
self.logger().warn("Initializing persistent storage from dict")
113+
LOGGER.info("Initializing persistent storage from dict")
115114

116115
self._handle = chip.native.GetLibraryHandle()
117116
self._isActive = True
@@ -125,24 +124,24 @@ def __init__(self, path: str = None, jsonData: Dict = None):
125124
self._file.seek(0)
126125

127126
if (size != 0):
128-
self.logger().warn(f"Loading configuration from {path}...")
127+
LOGGER.info(f"Loading configuration from {path}...")
129128
self._jsonData = json.load(self._file)
130129
else:
131130
self._jsonData = {}
132131

133132
except Exception as ex:
134-
logging.error(ex)
135-
logging.critical(f"Could not load configuration from {path} - resetting configuration...")
133+
LOGGER.error(ex)
134+
LOGGER.critical(f"Could not load configuration from {path} - resetting configuration...")
136135
self._jsonData = {}
137136
else:
138137
self._jsonData = jsonData
139138

140139
if ('sdk-config' not in self._jsonData):
141-
logging.warn("No valid SDK configuration present - clearing out configuration")
140+
LOGGER.warn("No valid SDK configuration present - clearing out configuration")
142141
self._jsonData['sdk-config'] = {}
143142

144143
if ('repl-config' not in self._jsonData):
145-
logging.warn("No valid REPL configuration present - clearing out configuration")
144+
LOGGER.warn("No valid REPL configuration present - clearing out configuration")
146145
self._jsonData['repl-config'] = {}
147146

148147
# Clear out the file so that calling 'Commit' will re-open the file at that time in write mode.
@@ -166,7 +165,6 @@ def Commit(self):
166165
''' Commits the cached JSON configuration to file (if one was provided in the constructor).
167166
Otherwise, this is a no-op.
168167
'''
169-
self.logger().info("Committing...")
170168

171169
if (self._path is None):
172170
return
@@ -175,9 +173,8 @@ def Commit(self):
175173
try:
176174
self._file = open(self._path, 'w')
177175
except Exception as ex:
178-
logging.warn(
179-
f"Could not open {self._path} for writing configuration. Error:")
180-
logging.warn(ex)
176+
LOGGER.error(
177+
f"Could not open {self._path} for writing configuration. Error: {ex}")
181178
return
182179

183180
self._file.seek(0)
@@ -188,7 +185,7 @@ def Commit(self):
188185
def SetReplKey(self, key: str, value):
189186
''' Set a REPL key to a specific value. Creates the key if one doesn't exist already.
190187
'''
191-
self.logger().info(f"SetReplKey: {key} = {value}")
188+
LOGGER.debug(f"SetReplKey: {key} = {value}")
192189

193190
if (key is None or key == ''):
194191
raise ValueError("Invalid Key")
@@ -212,7 +209,7 @@ def GetReplKey(self, key: str):
212209
def SetSdkKey(self, key: str, value: bytes):
213210
''' Set an SDK key to a specific value. Creates the key if one doesn't exist already.
214211
'''
215-
self.logger().info(f"SetSdkKey: {key} = {value}")
212+
LOGGER.debug(f"SetSdkKey: {key} = {value}")
216213

217214
if (key is None or key == ''):
218215
raise ValueError("Invalid Key")
@@ -236,7 +233,7 @@ def GetSdkKey(self, key: str):
236233
def DeleteSdkKey(self, key: str):
237234
''' Deletes an SDK key if one exists.
238235
'''
239-
self.logger().info(f"DeleteSdkKey: {key}")
236+
LOGGER.debug(f"DeleteSdkKey: {key}")
240237

241238
del (self._jsonData['sdk-config'][key])
242239
self.Commit()

0 commit comments

Comments
 (0)