Logging oddity: handlers mandatory in every single logger?

Jean-Michel Pichavant jeanmichel at sequans.com
Wed Feb 3 08:32:01 EST 2010


Masklinn wrote:
> On 3 Feb 2010, at 11:50 , Jean-Michel Pichavant wrote:
>   
>> You don't neeed to check the code for that ! It is written in the documentation. The logging module designer choose to ask for a level, not a level name, possibly because 2 different levels can have the same name.
>>
>>     
> Nope, 2 different levels cannot have the same name: levels are currently stored in a dict of string:level and level:string, so you can't have 2 names for the same level, and you can't have 2 levels with the same name either.
>
>   
import logging
logging.addLevelName(5, 'test')
logging.addLevelName(6, 'test')

logging._levelNames
{0: 'NOTSET',
 5: 'test',
 6: 'test',
 10: 'DEBUG',
 20: 'INFO',
 30: 'WARNING',
 40: 'ERROR',
 50: 'CRITICAL',
 'CRITICAL': 50,
 'DEBUG': 10,
 'ERROR': 40,
 'INFO': 20,
 'NOTSET': 0,
 'WARN': 30,
 'WARNING': 30,
 'test': 6}

now quoting the doc:

logging.addLevelName(/lvl/, /levelName/)
    Associates level /lvl/ with text /levelName/ in an internal
    dictionary, which is *used to map numeric levels to a textual
    representation*, for example when a Formatter
    <http://docs.python.org/library/logging.html#logging.Formatter>
    formats a message. This function can also be used to define your own
    levels. The only constraints are that all levels used must be
    registered using this function, levels should be positive integers
    and they should increase in increasing order of severity.


int -> string is the public association
string- > int is an internal hack to map easilty map Level name to their 
int identifier. This is used for the config file, where you specify a 
string not an int (you vrite level=DEBUG, not level=10)

Look at the builtin WARNING & WARN level, two different names for the 
same level.

In any case, you have to trust the documentation and public interface 
signature. Introspecting the code can be misleading. Now I better 
understand your initial concern.

>>>> the field handlers must be defined even if empty.
>>>>    
>>>>         
>>> Ah, interesting, I didn't think it could be defined as empty.
>>>
>>> Which makes the requirement to have an empty ``handler`` completely nonsensical, doesn't it?
>>>       
>> 'completeley nonsensical' is overstating.  It make sense to state that your handler list is empty, when it is empty.
>>     
> Programmatically, that's implied in the fact that you aren't specifying it. Why wouldn't it be in the config file? Why the asymetry here?
>
>   
Note how progammatically the list of handlers is set to an empty list. 
The attribute handlers is always set, so the config file field shall be :o)

In [11]: logger = logging.getLogger('test')

In [12]: logger.handlers
Out[12]: []



JM



More information about the Python-list mailing list