Skip to content

Commit 58bab0a

Browse files
committed
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 <[email protected]>
1 parent a9e52d0 commit 58bab0a

File tree

3 files changed

+20
-9
lines changed

3 files changed

+20
-9
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
11
import logging
22

3-
logging.warning("test")
3+
logging.debug("test - debug") # ignored by default
4+
logging.info("test - info") # ignored by default
5+
logging.warning("test - warning")
6+
logging.error("test - error")
7+
logging.critical("test - critical")

python-stdlib/logging/examples/root_logger.py

+1
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@
55
handler.setFormatter(logging.Formatter("[%(levelname)s]:%(name)s:%(message)s"))
66
logging.info("hello upy")
77
logging.getLogger("child").info("hello 2")
8+
logging.getLogger("child").debug("hello 2")

python-stdlib/logging/logging.py

+14-8
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
1+
from micropython import const
2+
13
import sys
24
import time
35

46
if hasattr(time, "strftime"):
57
from time import strftime
68

7-
CRITICAL = 50
8-
ERROR = 40
9-
WARNING = 30
10-
INFO = 20
11-
DEBUG = 10
12-
NOTSET = 0
9+
CRITICAL = const(50)
10+
ERROR = const(40)
11+
WARNING = const(30)
12+
INFO = const(20)
13+
DEBUG = const(10)
14+
NOTSET = const(0)
15+
16+
_DEFAULT_LEVEL = const(WARNING)
1317

1418
_level_dict = {
1519
CRITICAL: "CRITICAL",
@@ -22,7 +26,6 @@
2226

2327
_loggers = {}
2428
_stream = sys.stderr
25-
_level = INFO
2629
_default_fmt = "%(levelname)s:%(name)s:%(message)s"
2730
_default_datefmt = "%Y-%m-%d %H:%M:%S"
2831

@@ -115,7 +118,10 @@ def setLevel(self, level):
115118
self.level = level
116119

117120
def isEnabledFor(self, level):
118-
return level >= (self.level or _level)
121+
return level >= self.getEffectiveLevel()
122+
123+
def getEffectiveLevel(self):
124+
return self.level or getLogger().level or _DEFAULT_LEVEL
119125

120126
def log(self, level, msg, *args):
121127
if self.isEnabledFor(level):

0 commit comments

Comments
 (0)