Skip to content

bpo-43858: Add logging.getLevelNamesMapping() #26459

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
8 changes: 8 additions & 0 deletions Doc/library/logging.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1111,6 +1111,14 @@ functions.
.. note:: If you are thinking of defining your own levels, please see the
section on :ref:`custom-levels`.

.. function:: getLevelNamesMapping()

Returns a mapping from level names to their corresponding logging
levels. The returned mapping is copied from internal mapping on each call to this
function.

.. versionadded:: 3.11

.. function:: getLevelName(level)

Returns the textual or numeric representation of logging level *level*.
Expand Down
5 changes: 4 additions & 1 deletion Lib/logging/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass',
'info', 'log', 'makeLogRecord', 'setLoggerClass', 'shutdown',
'warn', 'warning', 'getLogRecordFactory', 'setLogRecordFactory',
'lastResort', 'raiseExceptions']
'lastResort', 'raiseExceptions', 'getLevelNamesMapping']

import threading

Expand Down Expand Up @@ -116,6 +116,9 @@
'NOTSET': NOTSET,
}

def getLevelNamesMapping():
return _nameToLevel.copy()

def getLevelName(level):
"""
Return the textual or numeric representation of logging level 'level'.
Expand Down
4 changes: 4 additions & 0 deletions Lib/test/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -4390,6 +4390,10 @@ def rec():
self.assertNotIn("Cannot recover from stack overflow.", err)
self.assertEqual(rc, 1)

def test_get_level_names_mapping(self):
self.assertEqual(logging._nameToLevel, logging.getLevelNamesMapping())
self.assertNotEqual(id(logging._nameToLevel), id(logging.getLevelNamesMapping()))


class LogRecordTest(BaseTest):
def test_str_rep(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added a function that returns a copy of a dict of logging levels: func::`logging.getLevelNamesMapping()`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that I look at this: isn't the correct syntax:

:func:`logging.getLevelNamesMapping`

?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, well spotted!