उपयोग के अनुभव के एक गुच्छा के साथ मौजूदा सभी उत्तरों को मिलाकर, मुझे लगता है कि मैं उन सभी चीजों की एक सूची के साथ आया हूं, जिन्हें नए स्तर पर पूरी तरह से सहज उपयोग सुनिश्चित करने के लिए किए जाने की आवश्यकता है। नीचे दिए गए चरण मान लेते हैं कि आप TRACE
मूल्य के साथ एक नया स्तर जोड़ रहे हैं logging.DEBUG - 5 == 5
:
logging.addLevelName(logging.DEBUG - 5, 'TRACE')
नए स्तर पर आंतरिक रूप से पंजीकृत होने के लिए आमंत्रित करने की आवश्यकता है ताकि इसे नाम से संदर्भित किया जा सके।
logging
स्थिरता के लिए खुद को एक विशेषता के रूप में नए स्तर को जोड़ने की आवश्यकता है logging.TRACE = logging.DEBUG - 5
:।
- एक विधि जिसे मॉड्यूल में
trace
जोड़ने की आवश्यकता है logging
। यह सिर्फ तरह व्यवहार करना चाहिए debug
, info
आदि
- एक विधि जिसे
trace
वर्तमान में कॉन्फ़िगर किए गए लॉगर वर्ग में जोड़ने की आवश्यकता है। चूंकि यह 100% होने की गारंटी नहीं है logging.Logger
, इसलिए logging.getLoggerClass()
इसके बजाय उपयोग करें ।
नीचे दिए गए विधि में सभी चरणों का वर्णन किया गया है:
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
"""
if not methodName:
methodName = levelName.lower()
if hasattr(logging, levelName):
raise AttributeError('{} already defined in logging module'.format(levelName))
if hasattr(logging, methodName):
raise AttributeError('{} already defined in logging module'.format(methodName))
if hasattr(logging.getLoggerClass(), methodName):
raise AttributeError('{} already defined in logger class'.format(methodName))
# This method was inspired by the answers to Stack Overflow post
# http://stackoverflow.com/q/2183233/2988730, especially
# http://stackoverflow.com/a/13638084/2988730
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)