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

前端 未结 16 2328
旧时难觅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:21

    This question is rather old, but I just dealt with the same topic and found a way similiar to those already mentioned which appears a little cleaner to me. This was tested on 3.4, so I'm not sure whether the methods used exist in older versions:

    from logging import getLoggerClass, addLevelName, setLoggerClass, NOTSET
    
    VERBOSE = 5
    
    class MyLogger(getLoggerClass()):
        def __init__(self, name, level=NOTSET):
            super().__init__(name, level)
    
            addLevelName(VERBOSE, "VERBOSE")
    
        def verbose(self, msg, *args, **kwargs):
            if self.isEnabledFor(VERBOSE):
                self._log(VERBOSE, msg, args, **kwargs)
    
    setLoggerClass(MyLogger)
    

提交回复
热议问题