[Tutor] Extending logging module

Kent Johnson kent37 at tds.net
Thu Aug 9 21:40:21 CEST 2007

jay wrote:
> I have a working solution for this, based largely on what Kent posted.  
> Thought I would post it for others in case your either curious, or need 
> to do this in the future.  There are probably other ways to do this.
> It works quite nicely, though its a lot of repeated 
> code if you have to define several new levels.

Here is a *completely untested off-the-top-of-my-head* rewrite for 
logging.addLevelName() that does this for you and saves having to repeat 
the function definitions. Maybe this could be used to create the 
standard logging functions too!

def addLevelName(level, levelName):
     Associate 'levelName' with 'level'.

     This is used when converting levels to text during message formatting.
     import logging
     try:    #unlikely to cause an exception, but you never know...
         _levelNames[level] = levelName
         _levelNames[levelName] = level

         lowerName = levelName.lower()

         # define a new Logger function for the new level
         # this is like existing info, critical, debug...etc
         def Logger_func(self, msg, *args, **kwargs):
             if self.manager.disable >= level:
             if level >= self.getEffectiveLevel():
                 self._log(level, msg, args, **kwargs)

         # Add the new function to the Logger class
         setattr(logging.Logger, lowerName, Logger_func)

         # define a new root level logging function
         # this is like existing info, critical, debug...etc
         def root_func(msg, *args, **kwargs):
             if len(root.handlers) == 0:
             Logger_func(root, (msg,)+args, kwargs)

         # make the root level function known
         setattr(logging, lowerName, root_func)



More information about the Tutor mailing list