logging: Fall back to root logger level for unset child.

Previously a child logger just uses the global default when unset.
Modified to matches the CPython behavior of using the parent's level.

Also implemented CPython's getEffectiveLevel() which provides a convenient
way to implement this. In our version, we only ever have one parent
(the root), so it only has to recurse one level.

Also set the default level to WARNING to match CPython.

Updated the examples to highlight the differences (but they now match).

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
pull/589/head
Jim Mussared 2022-12-19 21:55:54 +11:00
rodzic a9e52d085c
commit 58bab0add3
3 zmienionych plików z 20 dodań i 9 usunięć

Wyświetl plik

@ -1,3 +1,7 @@
import logging import logging
logging.warning("test") logging.debug("test - debug") # ignored by default
logging.info("test - info") # ignored by default
logging.warning("test - warning")
logging.error("test - error")
logging.critical("test - critical")

Wyświetl plik

@ -5,3 +5,4 @@ for handler in logging.getLogger().handlers:
handler.setFormatter(logging.Formatter("[%(levelname)s]:%(name)s:%(message)s")) handler.setFormatter(logging.Formatter("[%(levelname)s]:%(name)s:%(message)s"))
logging.info("hello upy") logging.info("hello upy")
logging.getLogger("child").info("hello 2") logging.getLogger("child").info("hello 2")
logging.getLogger("child").debug("hello 2")

Wyświetl plik

@ -1,15 +1,19 @@
from micropython import const
import sys import sys
import time import time
if hasattr(time, "strftime"): if hasattr(time, "strftime"):
from time import strftime from time import strftime
CRITICAL = 50 CRITICAL = const(50)
ERROR = 40 ERROR = const(40)
WARNING = 30 WARNING = const(30)
INFO = 20 INFO = const(20)
DEBUG = 10 DEBUG = const(10)
NOTSET = 0 NOTSET = const(0)
_DEFAULT_LEVEL = const(WARNING)
_level_dict = { _level_dict = {
CRITICAL: "CRITICAL", CRITICAL: "CRITICAL",
@ -22,7 +26,6 @@ _level_dict = {
_loggers = {} _loggers = {}
_stream = sys.stderr _stream = sys.stderr
_level = INFO
_default_fmt = "%(levelname)s:%(name)s:%(message)s" _default_fmt = "%(levelname)s:%(name)s:%(message)s"
_default_datefmt = "%Y-%m-%d %H:%M:%S" _default_datefmt = "%Y-%m-%d %H:%M:%S"
@ -115,7 +118,10 @@ class Logger:
self.level = level self.level = level
def isEnabledFor(self, level): def isEnabledFor(self, level):
return level >= (self.level or _level) return level >= self.getEffectiveLevel()
def getEffectiveLevel(self):
return self.level or getLogger().level or _DEFAULT_LEVEL
def log(self, level, msg, *args): def log(self, level, msg, *args):
if self.isEnabledFor(level): if self.isEnabledFor(level):