How to add a custom loglevel to Python's logging facility

前端 未结 16 2317
旧时难觅i
旧时难觅i 2020-11-27 09:54

I\'d like to have loglevel TRACE (5) for my application, as I don\'t think that debug() is sufficient. Additionally log(5, msg) isn\'t what I want.

16条回答
  •  失恋的感觉
    2020-11-27 10:20

    @Eric S.

    Eric S.'s answer is excellent, but I learned by experimentation that this will always cause messages logged at the new debug level to be printed -- regardless of what the log level is set to. So if you make a new level number of 9, if you call setLevel(50), the lower level messages will erroneously be printed.

    To prevent that from happening, you need another line inside the "debugv" function to check if the logging level in question is actually enabled.

    Fixed example that checks if the logging level is enabled:

    import logging
    DEBUG_LEVELV_NUM = 9 
    logging.addLevelName(DEBUG_LEVELV_NUM, "DEBUGV")
    def debugv(self, message, *args, **kws):
        if self.isEnabledFor(DEBUG_LEVELV_NUM):
            # Yes, logger takes its '*args' as 'args'.
            self._log(DEBUG_LEVELV_NUM, message, args, **kws) 
    logging.Logger.debugv = debugv
    

    If you look at the code for class Logger in logging.__init__.py for Python 2.7, this is what all the standard log functions do (.critical, .debug, etc.).

    I apparently can't post replies to others' answers for lack of reputation... hopefully Eric will update his post if he sees this. =)

提交回复
热议问题