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

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

    based on pinned answer, i wrote a little method which automaticaly create new logging levels

    def set_custom_logging_levels(config={}):
        """
            Assign custom levels for logging
                config: is a dict, like
                {
                    'EVENT_NAME': EVENT_LEVEL_NUM,
                }
            EVENT_LEVEL_NUM can't be like already has logging module
            logging.DEBUG       = 10
            logging.INFO        = 20
            logging.WARNING     = 30
            logging.ERROR       = 40
            logging.CRITICAL    = 50
        """
        assert isinstance(config, dict), "Configuration must be a dict"
    
        def get_level_func(level_name, level_num):
            def _blank(self, message, *args, **kws):
                if self.isEnabledFor(level_num):
                    # Yes, logger takes its '*args' as 'args'.
                    self._log(level_num, message, args, **kws) 
            _blank.__name__ = level_name.lower()
            return _blank
    
        for level_name, level_num in config.items():
            logging.addLevelName(level_num, level_name.upper())
            setattr(logging.Logger, level_name.lower(), get_level_func(level_name, level_num))
    
    

    config may smth like that:

    new_log_levels = {
        # level_num is in logging.INFO section, that's why it 21, 22, etc..
        "FOO":      21,
        "BAR":      22,
    }
    

提交回复
热议问题