เมื่อรวมคำตอบที่มีอยู่ทั้งหมดเข้ากับประสบการณ์การใช้งานมากมายฉันคิดว่าฉันได้สร้างรายการสิ่งที่ต้องทำทั้งหมดเพื่อให้แน่ใจว่าการใช้งานระดับใหม่จะราบรื่นอย่างสมบูรณ์ ขั้นตอนด้านล่างนี้ถือว่าคุณกำลังเพิ่มระดับใหม่TRACEด้วยค่าlogging.DEBUG - 5 == 5 :
- logging.addLevelName(logging.DEBUG - 5, 'TRACE')จำเป็นต้องเรียกใช้เพื่อรับระดับใหม่ที่ลงทะเบียนภายในเพื่อให้สามารถอ้างอิงด้วยชื่อได้
- ระดับใหม่จะต้องมีการเพิ่มเป็นแอตทริบิวต์เพื่อตัวเองเพื่อความมั่นคง:logginglogging.TRACE = logging.DEBUG - 5
- traceต้องเพิ่มเมธอดที่เรียกว่าลงใน- loggingโมดูล มันควรประพฤติเช่นเดียว- debug,- infoฯลฯ
- traceต้องเพิ่มเมธอดที่เรียกว่าไปยังคลาส logger ที่กำหนดค่าไว้ในปัจจุบัน เนื่องจากไม่รับประกัน 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)