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

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

    Tips for creating a custom logger:

    1. Do not use _log, use log (you don't have to check isEnabledFor)
    2. the logging module should be the one creating instance of the custom logger since it does some magic in getLogger, so you will need to set the class via setLoggerClass
    3. You do not need to define __init__ for the logger, class if you are not storing anything
    # Lower than debug which is 10
    TRACE = 5
    class MyLogger(logging.Logger):
        def trace(self, msg, *args, **kwargs):
            self.log(TRACE, msg, *args, **kwargs)
    

    When calling this logger use setLoggerClass(MyLogger) to make this the default logger from getLogger

    logging.setLoggerClass(MyLogger)
    log = logging.getLogger(__name__)
    # ...
    log.trace("something specific")
    

    You will need to setFormatter, setHandler, and setLevel(TRACE) on the handler and on the log itself to actually se this low level trace

提交回复
热议问题