Skip to content

Commit 8b93f0e

Browse files
authored
bpo-43858: Add logging.getLevelNamesMapping() (GH-26459)
Added a function that returns a copy of a dict of logging levels.
1 parent 4846ea9 commit 8b93f0e

File tree

4 files changed

+21
-1
lines changed

4 files changed

+21
-1
lines changed

Doc/library/logging.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1111,6 +1111,14 @@ functions.
11111111
.. note:: If you are thinking of defining your own levels, please see the
11121112
section on :ref:`custom-levels`.
11131113

1114+
.. function:: getLevelNamesMapping()
1115+
1116+
Returns a mapping from level names to their corresponding logging levels. For example, the
1117+
string "CRITICAL" maps to :const:`CRITICAL`. The returned mapping is copied from an internal
1118+
mapping on each call to this function.
1119+
1120+
.. versionadded:: 3.11
1121+
11141122
.. function:: getLevelName(level)
11151123

11161124
Returns the textual or numeric representation of logging level *level*.

Lib/logging/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass',
3838
'info', 'log', 'makeLogRecord', 'setLoggerClass', 'shutdown',
3939
'warn', 'warning', 'getLogRecordFactory', 'setLogRecordFactory',
40-
'lastResort', 'raiseExceptions']
40+
'lastResort', 'raiseExceptions', 'getLevelNamesMapping']
4141

4242
import threading
4343

@@ -116,6 +116,9 @@
116116
'NOTSET': NOTSET,
117117
}
118118

119+
def getLevelNamesMapping():
120+
return _nameToLevel.copy()
121+
119122
def getLevelName(level):
120123
"""
121124
Return the textual or numeric representation of logging level 'level'.

Lib/test/test_logging.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4390,6 +4390,14 @@ def rec():
43904390
self.assertNotIn("Cannot recover from stack overflow.", err)
43914391
self.assertEqual(rc, 1)
43924392

4393+
def test_get_level_names_mapping(self):
4394+
mapping = logging.getLevelNamesMapping()
4395+
self.assertEqual(logging._nameToLevel, mapping) # value is equivalent
4396+
self.assertIsNot(logging._nameToLevel, mapping) # but not the internal data
4397+
new_mapping = logging.getLevelNamesMapping() # another call -> another copy
4398+
self.assertIsNot(mapping, new_mapping) # verify not the same object as before
4399+
self.assertEqual(mapping, new_mapping) # but equivalent in value
4400+
43934401

43944402
class LogRecordTest(BaseTest):
43954403
def test_str_rep(self):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Added a function that returns a copy of a dict of logging levels: :func:`logging.getLevelNamesMapping`

0 commit comments

Comments
 (0)