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-pythons-logging-facility/13638084#13638084
 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?
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/CKZLNWNIXURL7PP674STUFKEI45XDNKD/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to