Allow adding custom logging levels as attributes
I have just been writing some code in which I define a custom log level with the logging module. I wanted to call the new log level as an attribute but currently the logging library lacks a nice way to do this. I know that in the docs https://docs.python.org/3/howto/logging.html#custom-levels it discourages creating custom log levels so perhaps this was why there is no way to do this. This https://stackoverflow.com/questions/2183233/how-to-add-a-custom-loglevel-to-... StackOverflow solution allows for the syntax I was after, but it is hard to understand for someone looking at the code. import logging CUSTOM_LEVEL = 31 CUSTOM_LEVEL_NAME = 'CUSTOM_WARNING' def custom_warning(self, message, *args, **kwargs): if logger.isEnabledFor(CUSTOM_LEVEL): logger._log(CUSTOM_LEVEL, message, args, **kwargs) logging.Logger.custom_warning = custom_warning logger = logging.getLogger(__name__) logger.warning('a warning here!') logger.custom_warning('a custom warning!') I would propose something like logger.addCustomLevel(CUSTOM_LEVEL, CUSTOM_LEVEL_NAME) There are some obvious limitations to this approach, all level names would also have to be valid function names otherwise something like logger.addCustomLevel(CUSTOM_LEVEL, "1 2 3") would be an issue what does everybody think?
participants (1)
-
harry.lees@gmail.com