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

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

    I find it easier to create a new attribute for the logger object that passes the log() function. I think the logger module provides the addLevelName() and the log() for this very reason. Thus no subclasses or new method needed.

    import logging
    
    @property
    def log(obj):
        logging.addLevelName(5, 'TRACE')
        myLogger = logging.getLogger(obj.__class__.__name__)
        setattr(myLogger, 'trace', lambda *args: myLogger.log(5, *args))
        return myLogger
    

    now

    mylogger.trace('This is a trace message')
    

    should work as expected.

提交回复
热议问题