← index #979PR #806
Likely Duplicate · medium · value 0.385
QUERY · ISSUE

logging.basicConfig(force=False) on empty handler list never initializes Formatter and Handler

openby nielsson4711opened 2025-02-25updated 2025-02-26

Aiming to add minimalistic logging capabilities soon within starting phase of a micropythion program, one would call:

#minimalistic
logging.basicConfig(stream=stream.sys level=logging.DEBUG)
logger = logging.getLogger('thelog')

Aiming to get a fancy timestamp and information ordering, the call could look like:

# explicit formatting
log_fmt_mipy = "%(name)s - %(levelname)s - %(message)s"
log_fmt_dat_mipy = "%(asctime)s.%(msecs)03d"
logging.basicConfig(stream=stream.sys level=logging.DEBUG)
logger = logging.getLogger('thelog')

The Object "logger" as Logger instance on either case will NEVER get a working Handler and Formatter upon initialization. This is because logging.basicConfig() in (current) line 235 evaluates the list object Logger.handlers instead of the integer number Logger.hasHandlers().

NOTE: Initialization of a date format of type "asctime" within micropython, as shown in the code above, is not (yet) supported (by design) and thus requires explicit implementation efforts.

CANDIDATE · PULL REQUEST

logging.py: CPython-compatible logging improvements.

openby ned-pcsopened 2024-02-15updated 2024-03-21

This PR allows for logging handlers to be added to the root logger and then used by non-root loggers that don't have their own handlers.

It replaces #750 (in which I forgot a period at the end of a commit message title).

It also adds the (CPython-compatible) handlers argument to logging.basicConfig() to ease this initialization:

    import logging
    sh = logging.StreamHandler()
    fh = logging.FileHandler("my.log", mode="a")
    logging.basicConfig(handlers=[sh, fh])

    root_logger = logging.getLogger() # uses sh and fh
    another_logger = logging.getLogger("another") # inherits handlers

It also adds the Logger.removeHandler() method and avoids repeated handler addition.

It also adds the flush() method to StreamHandler and its subclasses.

It also correctly calls the superclass constructor from the StreamHandler constructor and uses a default formatter if a Handler has none set (as in PR #710).

2 comments
ned-pcs · 2024-02-15

build failure is due to an unrelated manifest.py issue.

projectgus · 2024-02-19

@ned-pcs If you rebase on master then the build should be fixed now.

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