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

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

    While we have already plenty of correct answers, the following is in my opinion more pythonic:

    import logging
    
    from functools import partial, partialmethod
    
    logging.TRACE = 5
    logging.addLevelName(logging.TRACE, 'TRACE')
    logging.Logger.trace = partialmethod(logging.Logger.log, logging.TRACE)
    logging.trace = partial(logging.log, logging.TRACE)
    

    If you want to use mypy on your code, it is recommended to add # type: ignore to suppress warnings from adding attribute.

提交回复
热议问题