← index #691PR #710
Duplicate · high · value 4.937
QUERY · ISSUE

logging.StreamHandler should call super().__init__()

openby uldaopened 2023-06-22updated 2023-08-05

logging.StreamHandler inherits from logging.Handler but does not call super().init()
so it misses to initialize level and formatter instance variables

by the way, logging.Handler should initialize formatter to a working formatter, not None.
e.g. if you create and add a new StreamHandler, it has no formatter set by default and any logging will generate an exception.

1 comment
colin-nolan · 2023-08-05

I also encountered this issue, and have added a PR to fix in #710.

CANDIDATE · PULL REQUEST

logging: add call to superclass initialiser; set default formatter

openby colin-nolanopened 2023-08-05updated 2024-01-28

Addresses minor issues in logging module, reported in https://github.com/micropython/micropython-lib/issues/691.

Change 1: Makes subclasses of logging.Handler call the superclasses' initialiser

CPython:

>>> import logging
>>> logger = logging.StreamHandler()
>>> logger.level 
0

MicroPython (master):

>>> logger = logging.StreamHandler()
>>> logger.level
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'StreamHandler' object has no attribute 'level'

MicroPython (this branch):

>>> logger = logging.StreamHandler()
>>> logger.level
0

Change 2: Sets a default formatter if not set

CPython:

>>> record = logging.LogRecord("Test", 20, "/example", 1, "Hello", (), None)
>>> logger.emit(record)
Hello

MicroPython (master + fix 1):

>>> record = logging.LogRecord()
>>> record.set("Test", 20, "Hello")
>>> logger.emit(record)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "logging.py", line 72, in emit
  File "logging.py", line 56, in format
AttributeError: 'NoneType' object has no attribute 'format'

MicroPython (this branch):

>>> record = logging.LogRecord()
>>> record.set("Test", 20, "Hello")
>>> logger.emit(record)
INFO:Test:Hello

The CPython implementation of logging can be found here:
https://github.com/python/cpython/blob/main/Lib/logging/init.py

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied