Skip to content

Commit 44526d2

Browse files
authoredJun 4, 2024··
[Python] Remove obsolete logging callbacks (#33718)
Since #5024 there is a new logging callback working. The old code has partially been removed in #4690, but never completely. Drop the old logging code for good.
1 parent 9217d22 commit 44526d2

File tree

2 files changed

+2
-158
lines changed

2 files changed

+2
-158
lines changed
 

‎src/controller/python/ChipDeviceController-ScriptBinding.cpp

-12
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,6 @@ PyChipError pychip_DeviceCommissioner_CloseBleConnection(chip::Controller::Devic
212212

213213
const char * pychip_Stack_ErrorToString(ChipError::StorageType err);
214214
const char * pychip_Stack_StatusReportToString(uint32_t profileId, uint16_t statusCode);
215-
void pychip_Stack_SetLogFunct(LogMessageFunct logFunct);
216215

217216
PyChipError pychip_GetConnectedDeviceByNodeId(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId,
218217
chip::Controller::Python::PyObject * context, DeviceAvailableFunc callback);
@@ -863,17 +862,6 @@ uint64_t pychip_GetCommandSenderHandle(chip::DeviceProxy * device)
863862
return 0;
864863
}
865864

866-
void pychip_Stack_SetLogFunct(LogMessageFunct logFunct)
867-
{
868-
// TODO: determine if log redirection is supposed to be functioning in CHIP
869-
//
870-
// Background: original log baseline supported 'redirect logs to this
871-
// function' however CHIP does not currently provide this.
872-
//
873-
// Ideally log redirection should work so that python code can do things
874-
// like using the log module.
875-
}
876-
877865
PyChipError pychip_DeviceController_PostTaskOnChipThread(ChipThreadTaskRunnerFunct callback, void * pythonContext)
878866
{
879867
if (callback == nullptr || pythonContext == nullptr)

‎src/controller/python/chip/ChipStack.py

+2-146
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,11 @@
2828

2929
import asyncio
3030
import builtins
31-
import logging
3231
import os
33-
import sys
34-
import time
35-
from ctypes import CFUNCTYPE, Structure, c_bool, c_char_p, c_int64, c_uint8, c_uint16, c_uint32, c_void_p, py_object, pythonapi
32+
from ctypes import CFUNCTYPE, Structure, c_bool, c_char_p, c_uint16, c_uint32, c_void_p, py_object, pythonapi
3633
from threading import Condition, Event, Lock
3734

3835
import chip.native
39-
from chip.logging import LOG_CATEGORY_AUTOMATION, LOG_CATEGORY_DETAIL, LOG_CATEGORY_ERROR, LOG_CATEGORY_PROGRESS
4036
from chip.native import PyChipError
4137

4238
from .ChipUtility import ChipUtility
@@ -76,51 +72,6 @@ class DeviceStatusStruct(Structure):
7672
]
7773

7874

79-
class LogCategory(object):
80-
"""Debug logging categories used by chip."""
81-
82-
@staticmethod
83-
def categoryToLogLevel(cat):
84-
if cat == LOG_CATEGORY_ERROR:
85-
return logging.ERROR
86-
elif cat == LOG_CATEGORY_PROGRESS:
87-
return logging.INFO
88-
elif cat in (LOG_CATEGORY_DETAIL, LOG_CATEGORY_AUTOMATION):
89-
return logging.DEBUG
90-
else:
91-
return logging.NOTSET
92-
93-
94-
class ChipLogFormatter(logging.Formatter):
95-
"""A custom logging.Formatter for logging chip library messages."""
96-
97-
def __init__(
98-
self,
99-
datefmt=None,
100-
logModulePrefix=False,
101-
logLevel=False,
102-
logTimestamp=False,
103-
logMSecs=True,
104-
):
105-
fmt = "%(message)s"
106-
if logModulePrefix:
107-
fmt = "CHIP:%(chip-module)s: " + fmt
108-
if logLevel:
109-
fmt = "%(levelname)s:" + fmt
110-
if datefmt is not None or logTimestamp:
111-
fmt = "%(asctime)s " + fmt
112-
super(ChipLogFormatter, self).__init__(fmt=fmt, datefmt=datefmt)
113-
self.logMSecs = logMSecs
114-
115-
def formatTime(self, record, datefmt=None):
116-
if datefmt is None:
117-
timestampStr = time.strftime("%Y-%m-%d %H:%M:%S%z")
118-
if self.logMSecs:
119-
timestampUS = record.__dict__.get("timestamp-usec", 0)
120-
timestampStr = "%s.%03ld" % (timestampStr, timestampUS / 1000)
121-
return timestampStr
122-
123-
12475
class AsyncCallableHandle:
12576
def __init__(self, callback):
12677
self._callback = callback
@@ -185,15 +136,12 @@ def __call__(self):
185136
pythonapi.Py_DecRef(py_object(self))
186137

187138

188-
_LogMessageFunct = CFUNCTYPE(
189-
None, c_int64, c_int64, c_char_p, c_uint8, c_char_p)
190139
_ChipThreadTaskRunnerFunct = CFUNCTYPE(None, py_object)
191140

192141

193142
@_singleton
194143
class ChipStack(object):
195-
def __init__(self, persistentStoragePath: str, installDefaultLogHandler=True,
196-
bluetoothAdapter=None, enableServerInteractions=True):
144+
def __init__(self, persistentStoragePath: str, enableServerInteractions=True):
197145
builtins.enableDebugMode = False
198146

199147
# TODO: Probably no longer necessary, see https://github.com/project-chip/connectedhomeip/issues/33321.
@@ -206,8 +154,6 @@ def __init__(self, persistentStoragePath: str, installDefaultLogHandler=True,
206154
self.callbackRes = None
207155
self.commissioningEventRes = None
208156
self.openCommissioningWindowPincode = {}
209-
self._activeLogFunct = None
210-
self.addModulePrefixToLogMessage = True
211157
self._enableServerInteractions = enableServerInteractions
212158

213159
#
@@ -216,50 +162,6 @@ def __init__(self, persistentStoragePath: str, installDefaultLogHandler=True,
216162
#
217163
self._loadLib()
218164

219-
# Arrange to log output from the chip library to a python logger object with the
220-
# name 'chip.ChipStack'. If desired, applications can override this behavior by
221-
# setting self.logger to a different python logger object, or by calling setLogFunct()
222-
# with their own logging function.
223-
self.logger = logging.getLogger(__name__)
224-
self.setLogFunct(self.defaultLogFunct)
225-
226-
# Determine if there are already handlers installed for the logger. Python 3.5+
227-
# has a method for this; on older versions the check has to be done manually.
228-
if hasattr(self.logger, "hasHandlers"):
229-
hasHandlers = self.logger.hasHandlers()
230-
else:
231-
hasHandlers = False
232-
logger = self.logger
233-
while logger is not None:
234-
if len(logger.handlers) > 0:
235-
hasHandlers = True
236-
break
237-
if not logger.propagate:
238-
break
239-
logger = logger.parent
240-
241-
# If a logging handler has not already been initialized for 'chip.ChipStack',
242-
# or any one of its parent loggers, automatically configure a handler to log to
243-
# stdout. This maintains compatibility with a number of applications which expect
244-
# chip log output to go to stdout by default.
245-
#
246-
# This behavior can be overridden in a variety of ways:
247-
# - Initialize a different log handler before ChipStack is initialized.
248-
# - Pass installDefaultLogHandler=False when initializing ChipStack.
249-
# - Replace the StreamHandler on self.logger with a different handler object.
250-
# - Set a different Formatter object on the existing StreamHandler object.
251-
# - Reconfigure the existing ChipLogFormatter object.
252-
# - Configure chip to call an application-specific logging function by
253-
# calling self.setLogFunct().
254-
# - Call self.setLogFunct(None), which will configure the chip library
255-
# to log directly to stdout, bypassing python altogether.
256-
#
257-
if installDefaultLogHandler and not hasHandlers:
258-
logHandler = logging.StreamHandler(stream=sys.stdout)
259-
logHandler.setFormatter(ChipLogFormatter())
260-
self.logger.addHandler(logHandler)
261-
self.logger.setLevel(logging.DEBUG)
262-
263165
@_ChipThreadTaskRunnerFunct
264166
def HandleChipThreadRun(callback):
265167
callback()
@@ -292,49 +194,6 @@ def GetStorageManager(self):
292194
def enableServerInteractions(self):
293195
return self._enableServerInteractions
294196

295-
@property
296-
def defaultLogFunct(self):
297-
"""Returns a python callable which, when called, logs a message to the python logger object
298-
currently associated with the ChipStack object.
299-
The returned function is suitable for passing to the setLogFunct() method."""
300-
301-
def logFunct(timestamp, timestampUSec, moduleName, logCat, message):
302-
moduleName = ChipUtility.CStringToString(moduleName)
303-
message = ChipUtility.CStringToString(message)
304-
if self.addModulePrefixToLogMessage:
305-
message = "CHIP:%s: %s" % (moduleName, message)
306-
logLevel = LogCategory.categoryToLogLevel(logCat)
307-
msgAttrs = {
308-
"chip-module": moduleName,
309-
"timestamp": timestamp,
310-
"timestamp-usec": timestampUSec,
311-
}
312-
self.logger.log(logLevel, message, extra=msgAttrs)
313-
314-
return logFunct
315-
316-
def setLogFunct(self, logFunct):
317-
"""Set the function used by the chip library to log messages.
318-
The supplied object must be a python callable that accepts the following
319-
arguments:
320-
timestamp (integer)
321-
timestampUS (integer)
322-
module name (encoded UTF-8 string)
323-
log category (integer)
324-
message (encoded UTF-8 string)
325-
Specifying None configures the chip library to log directly to stdout."""
326-
if logFunct is None:
327-
logFunct = 0
328-
if not isinstance(logFunct, _LogMessageFunct):
329-
logFunct = _LogMessageFunct(logFunct)
330-
# TODO: Lock probably no longer necessary, see https://github.com/project-chip/connectedhomeip/issues/33321.
331-
with self.networkLock:
332-
# NOTE: ChipStack must hold a reference to the CFUNCTYPE object while it is
333-
# set. Otherwise it may get garbage collected, and logging calls from the
334-
# chip library will fail.
335-
self._activeLogFunct = logFunct
336-
self._ChipStackLib.pychip_Stack_SetLogFunct(logFunct)
337-
338197
def Shutdown(self):
339198
#
340199
# Terminate Matter thread and shutdown the stack.
@@ -484,9 +343,6 @@ def _loadLib(self):
484343
self._ChipStackLib.pychip_Stack_StatusReportToString.restype = c_char_p
485344
self._ChipStackLib.pychip_Stack_ErrorToString.argtypes = [c_uint32]
486345
self._ChipStackLib.pychip_Stack_ErrorToString.restype = c_char_p
487-
self._ChipStackLib.pychip_Stack_SetLogFunct.argtypes = [
488-
_LogMessageFunct]
489-
self._ChipStackLib.pychip_Stack_SetLogFunct.restype = PyChipError
490346

491347
self._ChipStackLib.pychip_DeviceController_PostTaskOnChipThread.argtypes = [
492348
_ChipThreadTaskRunnerFunct, py_object]

0 commit comments

Comments
 (0)
Please sign in to comment.