For some reason, in a Python application I am trying to modify, the logger is not logging anything. I traced the error to logging/__init__.py
def handle(self, record): """ Call the handlers for the specified record. This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied. """ if (not self.disabled) and self.filter(record): self.callHandlers(record)
I am not sure why, but self.disabled
is True
. Nowhere in the application this value is set and I don’t think any of the packages is changing it. The logger is instantiated as usual logger = logging.getLogger(__name__)
. When I set logger.disabled = False
before actually logging anything (before calling logger.info()
), the logger prints the expected log text. But if I don’t, it returns in handle()
without logging anything.
Is there any way I can debug this? Perhaps one can change the Logger
class so that some function is called whenever disabled
gets written to…
Advertisement
Answer
If you need to trace what code might set handler.disabled
to True (it is 0, so false, by default), you can replace the attribute with a property:
import logging import sys @property def disabled(self): try: return self._disabled except AttributeError: return False @disabled.setter def disabled(self, disabled): if disabled: frame = sys._getframe(1) print( f"{frame.f_code.co_filename}:{frame.f_lineno} " f"disabled the {self.name} logger" ) self._disabled = disabled logging.Logger.disabled = disabled
Demo from the interactive interpreter:
>>> import logging >>> logging.getLogger('foo.bar').disabled = True <stdin>:1 disabled the foo.bar logger
If you want to see the full stack, add from traceback import print_stack
, and inside the if disabled:
block, print_stack(frame)
.