Skip to content

Instantly share code, notes, and snippets.

@fschwar4
Created January 12, 2024 08:21
Show Gist options
  • Save fschwar4/e325ae38c84ffa637f767be24b01b287 to your computer and use it in GitHub Desktop.
Save fschwar4/e325ae38c84ffa637f767be24b01b287 to your computer and use it in GitHub Desktop.
Creating Custom/Unique Logger-Level for Python
def addLoggingLevel(levelName, levelNum, methodName=None):
"""Comprehensively adds a new logging level to the `logging` module and the
currently configured logging class.
`levelName` becomes an attribute of the `logging` module with the value
`levelNum`. `methodName` becomes a convenience method for both `logging`
itself and the class returned by `logging.getLoggerClass()` (usually just
`logging.Logger`). If `methodName` is not specified, `levelName.lower()` is
used.
To avoid accidental clobberings of existing attributes, this method will
raise an `AttributeError` if the level name is already an attribute of the
`logging` module or if the method name is already present
Example
-------
>>> addLoggingLevel('TRACE', logging.DEBUG - 5)
>>> logging.getLogger(__name__).setLevel('TRACE')
>>> logging.getLogger(__name__).trace('that worked')
>>> logging.trace('so did this')
>>> logging.TRACE
5
References:
This method was inspired by the answers to Stack Overflow post
http://stackoverflow.com/q/2183233/2988730, especially
http://stackoverflow.com/a/13638084/2988730.
"""
if not methodName:
methodName = levelName.lower()
try:
if hasattr(logging, levelName):
raise AttributeError('{} already defined in log module'.format(levelName))
if hasattr(logging, methodName):
raise AttributeError('{} already defined in log module'.format(methodName))
if hasattr(logging.getLoggerClass(), methodName):
raise AttributeError('{} already defined in logger class'.format(methodName))
except AttributeError as ae:
logging.warning(ae)
return
def logForLevel(self, message, *args, **kwargs):
if self.isEnabledFor(levelNum):
self._log(levelNum, message, args, **kwargs)
def logToRoot(message, *args, **kwargs):
logging.log(levelNum, message, *args, **kwargs)
logging.addLevelName(levelNum, levelName)
setattr(logging, levelName, levelNum)
setattr(logging.getLoggerClass(), methodName, logForLevel)
setattr(logging, methodName, logToRoot)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment