Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes
logging.config.DictConfigurator Class Reference
Inheritance diagram for logging.config.DictConfigurator:
Inheritance graph
[legend]
Collaboration diagram for logging.config.DictConfigurator:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def configure
def configure_formatter
def configure_filter
def add_filters
def configure_handler
def add_handlers
def common_logger_config
def configure_logger
def configure_root
def resolve
def ext_convert
def cfg_convert
def convert
def configure_custom
def as_tuple

Public Attributes

 config
_PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt
struct _typeobjectob_type

Static Public Attributes

tuple CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')
tuple WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
tuple DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*')
tuple INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*')
tuple DIGIT_PATTERN = re.compile(r'^\d+$')
dictionary value_converters
tuple importer = staticmethod(__import__)

Detailed Description

Configure logging using a dictionary-like object to describe the
configuration.

Definition at line 491 of file config.py.


Member Function Documentation

def logging.config.DictConfigurator.add_filters (   self,
  filterer,
  filters 
)
Add filters to a filterer from a list of names.

Definition at line 672 of file config.py.

00672 
00673     def add_filters(self, filterer, filters):
00674         """Add filters to a filterer from a list of names."""
00675         for f in filters:
00676             try:
00677                 filterer.addFilter(self.config['filters'][f])
00678             except Exception as e:
00679                 raise ValueError('Unable to add filter %r: %s' % (f, e))

Here is the caller graph for this function:

def logging.config.DictConfigurator.add_handlers (   self,
  logger,
  handlers 
)
Add handlers to a logger from a list of names.

Definition at line 733 of file config.py.

00733 
00734     def add_handlers(self, logger, handlers):
00735         """Add handlers to a logger from a list of names."""
00736         for h in handlers:
00737             try:
00738                 logger.addHandler(self.config['handlers'][h])
00739             except Exception as e:
00740                 raise ValueError('Unable to add handler %r: %s' % (h, e))

Here is the caller graph for this function:

def logging.config.BaseConfigurator.as_tuple (   self,
  value 
) [inherited]
Utility function which converts lists to tuples.

Definition at line 485 of file config.py.

00485 
00486     def as_tuple(self, value):
00487         """Utility function which converts lists to tuples."""
00488         if isinstance(value, list):
00489             value = tuple(value)
00490         return value

Here is the caller graph for this function:

def logging.config.BaseConfigurator.cfg_convert (   self,
  value 
) [inherited]
Default converter for the cfg:// protocol.

Definition at line 409 of file config.py.

00409 
00410     def cfg_convert(self, value):
00411         """Default converter for the cfg:// protocol."""
00412         rest = value
00413         m = self.WORD_PATTERN.match(rest)
00414         if m is None:
00415             raise ValueError("Unable to convert %r" % value)
00416         else:
00417             rest = rest[m.end():]
00418             d = self.config[m.groups()[0]]
00419             #print d, rest
00420             while rest:
00421                 m = self.DOT_PATTERN.match(rest)
00422                 if m:
00423                     d = d[m.groups()[0]]
00424                 else:
00425                     m = self.INDEX_PATTERN.match(rest)
00426                     if m:
00427                         idx = m.groups()[0]
00428                         if not self.DIGIT_PATTERN.match(idx):
00429                             d = d[idx]
00430                         else:
00431                             try:
00432                                 n = int(idx) # try as number first (most likely)
00433                                 d = d[n]
00434                             except TypeError:
00435                                 d = d[idx]
00436                 if m:
00437                     rest = rest[m.end():]
00438                 else:
00439                     raise ValueError('Unable to convert '
00440                                      '%r at %r' % (value, rest))
00441         #rest should be empty
00442         return d

def logging.config.DictConfigurator.common_logger_config (   self,
  logger,
  config,
  incremental = False 
)
Perform configuration which is common to root and non-root loggers.

Definition at line 741 of file config.py.

00741 
00742     def common_logger_config(self, logger, config, incremental=False):
00743         """
00744         Perform configuration which is common to root and non-root loggers.
00745         """
00746         level = config.get('level', None)
00747         if level is not None:
00748             logger.setLevel(logging._checkLevel(level))
00749         if not incremental:
00750             #Remove any existing handlers
00751             for h in logger.handlers[:]:
00752                 logger.removeHandler(h)
00753             handlers = config.get('handlers', None)
00754             if handlers:
00755                 self.add_handlers(logger, handlers)
00756             filters = config.get('filters', None)
00757             if filters:
00758                 self.add_filters(logger, filters)

Here is the call graph for this function:

Here is the caller graph for this function:

def logging.config.DictConfigurator.configure (   self)
Do the configuration.

Definition at line 497 of file config.py.

00497 
00498     def configure(self):
00499         """Do the configuration."""
00500 
00501         config = self.config
00502         if 'version' not in config:
00503             raise ValueError("dictionary doesn't specify a version")
00504         if config['version'] != 1:
00505             raise ValueError("Unsupported version: %s" % config['version'])
00506         incremental = config.pop('incremental', False)
00507         EMPTY_DICT = {}
00508         logging._acquireLock()
00509         try:
00510             if incremental:
00511                 handlers = config.get('handlers', EMPTY_DICT)
00512                 for name in handlers:
00513                     if name not in logging._handlers:
00514                         raise ValueError('No handler found with '
00515                                          'name %r'  % name)
00516                     else:
00517                         try:
00518                             handler = logging._handlers[name]
00519                             handler_config = handlers[name]
00520                             level = handler_config.get('level', None)
00521                             if level:
00522                                 handler.setLevel(logging._checkLevel(level))
00523                         except Exception as e:
00524                             raise ValueError('Unable to configure handler '
00525                                              '%r: %s' % (name, e))
00526                 loggers = config.get('loggers', EMPTY_DICT)
00527                 for name in loggers:
00528                     try:
00529                         self.configure_logger(name, loggers[name], True)
00530                     except Exception as e:
00531                         raise ValueError('Unable to configure logger '
00532                                          '%r: %s' % (name, e))
00533                 root = config.get('root', None)
00534                 if root:
00535                     try:
00536                         self.configure_root(root, True)
00537                     except Exception as e:
00538                         raise ValueError('Unable to configure root '
00539                                          'logger: %s' % e)
00540             else:
00541                 disable_existing = config.pop('disable_existing_loggers', True)
00542 
00543                 logging._handlers.clear()
00544                 del logging._handlerList[:]
00545 
00546                 # Do formatters first - they don't refer to anything else
00547                 formatters = config.get('formatters', EMPTY_DICT)
00548                 for name in formatters:
00549                     try:
00550                         formatters[name] = self.configure_formatter(
00551                                                             formatters[name])
00552                     except Exception as e:
00553                         raise ValueError('Unable to configure '
00554                                          'formatter %r: %s' % (name, e))
00555                 # Next, do filters - they don't refer to anything else, either
00556                 filters = config.get('filters', EMPTY_DICT)
00557                 for name in filters:
00558                     try:
00559                         filters[name] = self.configure_filter(filters[name])
00560                     except Exception as e:
00561                         raise ValueError('Unable to configure '
00562                                          'filter %r: %s' % (name, e))
00563 
00564                 # Next, do handlers - they refer to formatters and filters
00565                 # As handlers can refer to other handlers, sort the keys
00566                 # to allow a deterministic order of configuration
00567                 handlers = config.get('handlers', EMPTY_DICT)
00568                 for name in sorted(handlers):
00569                     try:
00570                         handler = self.configure_handler(handlers[name])
00571                         handler.name = name
00572                         handlers[name] = handler
00573                     except Exception as e:
00574                         raise ValueError('Unable to configure handler '
00575                                          '%r: %s' % (name, e))
00576                 # Next, do loggers - they refer to handlers and filters
00577 
00578                 #we don't want to lose the existing loggers,
00579                 #since other threads may have pointers to them.
00580                 #existing is set to contain all existing loggers,
00581                 #and as we go through the new configuration we
00582                 #remove any which are configured. At the end,
00583                 #what's left in existing is the set of loggers
00584                 #which were in the previous configuration but
00585                 #which are not in the new configuration.
00586                 root = logging.root
00587                 existing = list(root.manager.loggerDict.keys())
00588                 #The list needs to be sorted so that we can
00589                 #avoid disabling child loggers of explicitly
00590                 #named loggers. With a sorted list it is easier
00591                 #to find the child loggers.
00592                 existing.sort(key=_encoded)
00593                 #We'll keep the list of existing loggers
00594                 #which are children of named loggers here...
00595                 child_loggers = []
00596                 #now set up the new ones...
00597                 loggers = config.get('loggers', EMPTY_DICT)
00598                 for name in loggers:
00599                     if name in existing:
00600                         i = existing.index(name) + 1 # look after name
00601                         prefixed = name + "."
00602                         pflen = len(prefixed)
00603                         num_existing = len(existing)
00604                         while i < num_existing:
00605                             if existing[i][:pflen] == prefixed:
00606                                 child_loggers.append(existing[i])
00607                             i += 1
00608                         existing.remove(name)
00609                     try:
00610                         self.configure_logger(name, loggers[name])
00611                     except Exception as e:
00612                         raise ValueError('Unable to configure logger '
00613                                          '%r: %s' % (name, e))
00614 
00615                 #Disable any old loggers. There's no point deleting
00616                 #them as other threads may continue to hold references
00617                 #and by disabling them, you stop them doing any logging.
00618                 #However, don't disable children of named loggers, as that's
00619                 #probably not what was intended by the user.
00620                 #for log in existing:
00621                 #    logger = root.manager.loggerDict[log]
00622                 #    if log in child_loggers:
00623                 #        logger.level = logging.NOTSET
00624                 #        logger.handlers = []
00625                 #        logger.propagate = True
00626                 #    elif disable_existing:
00627                 #        logger.disabled = True
00628                 _handle_existing_loggers(existing, child_loggers,
00629                                          disable_existing)
00630 
00631                 # And finally, do the root logger
00632                 root = config.get('root', None)
00633                 if root:
00634                     try:
00635                         self.configure_root(root)
00636                     except Exception as e:
00637                         raise ValueError('Unable to configure root '
00638                                          'logger: %s' % e)
00639         finally:
00640             logging._releaseLock()

Here is the call graph for this function:

Here is the caller graph for this function:

def logging.config.BaseConfigurator.configure_custom (   self,
  config 
) [inherited]
Configure an object with a user-supplied factory.

Definition at line 471 of file config.py.

00471 
00472     def configure_custom(self, config):
00473         """Configure an object with a user-supplied factory."""
00474         c = config.pop('()')
00475         if not hasattr(c, '__call__'):
00476             c = self.resolve(c)
00477         props = config.pop('.', None)
00478         # Check for valid identifiers
00479         kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
00480         result = c(**kwargs)
00481         if props:
00482             for name, value in props.items():
00483                 setattr(result, name, value)
00484         return result

Here is the call graph for this function:

Here is the caller graph for this function:

def logging.config.DictConfigurator.configure_filter (   self,
  config 
)
Configure a filter from a dictionary.

Definition at line 663 of file config.py.

00663 
00664     def configure_filter(self, config):
00665         """Configure a filter from a dictionary."""
00666         if '()' in config:
00667             result = self.configure_custom(config)
00668         else:
00669             name = config.get('name', '')
00670             result = logging.Filter(name)
00671         return result

Here is the call graph for this function:

Here is the caller graph for this function:

def logging.config.DictConfigurator.configure_formatter (   self,
  config 
)
Configure a formatter from a dictionary.

Definition at line 641 of file config.py.

00641 
00642     def configure_formatter(self, config):
00643         """Configure a formatter from a dictionary."""
00644         if '()' in config:
00645             factory = config['()'] # for use in exception handler
00646             try:
00647                 result = self.configure_custom(config)
00648             except TypeError as te:
00649                 if "'format'" not in str(te):
00650                     raise
00651                 #Name of parameter changed from fmt to format.
00652                 #Retry with old name.
00653                 #This is so that code can be used with older Python versions
00654                 #(e.g. by Django)
00655                 config['fmt'] = config.pop('format')
00656                 config['()'] = factory
00657                 result = self.configure_custom(config)
00658         else:
00659             fmt = config.get('format', None)
00660             dfmt = config.get('datefmt', None)
00661             result = logging.Formatter(fmt, dfmt)
00662         return result

Here is the call graph for this function:

Here is the caller graph for this function:

def logging.config.DictConfigurator.configure_handler (   self,
  config 
)
Configure a handler from a dictionary.

Definition at line 680 of file config.py.

00680 
00681     def configure_handler(self, config):
00682         """Configure a handler from a dictionary."""
00683         formatter = config.pop('formatter', None)
00684         if formatter:
00685             try:
00686                 formatter = self.config['formatters'][formatter]
00687             except Exception as e:
00688                 raise ValueError('Unable to set formatter '
00689                                  '%r: %s' % (formatter, e))
00690         level = config.pop('level', None)
00691         filters = config.pop('filters', None)
00692         if '()' in config:
00693             c = config.pop('()')
00694             if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
00695                 c = self.resolve(c)
00696             factory = c
00697         else:
00698             klass = self.resolve(config.pop('class'))
00699             #Special case for handler which refers to another handler
00700             if issubclass(klass, logging.handlers.MemoryHandler) and\
00701                 'target' in config:
00702                 try:
00703                     config['target'] = self.config['handlers'][config['target']]
00704                 except Exception as e:
00705                     raise ValueError('Unable to set target handler '
00706                                      '%r: %s' % (config['target'], e))
00707             elif issubclass(klass, logging.handlers.SMTPHandler) and\
00708                 'mailhost' in config:
00709                 config['mailhost'] = self.as_tuple(config['mailhost'])
00710             elif issubclass(klass, logging.handlers.SysLogHandler) and\
00711                 'address' in config:
00712                 config['address'] = self.as_tuple(config['address'])
00713             factory = klass
00714         kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
00715         try:
00716             result = factory(**kwargs)
00717         except TypeError as te:
00718             if "'stream'" not in str(te):
00719                 raise
00720             #The argument name changed from strm to stream
00721             #Retry with old name.
00722             #This is so that code can be used with older Python versions
00723             #(e.g. by Django)
00724             kwargs['strm'] = kwargs.pop('stream')
00725             result = factory(**kwargs)
00726         if formatter:
00727             result.setFormatter(formatter)
00728         if level is not None:
00729             result.setLevel(logging._checkLevel(level))
00730         if filters:
00731             self.add_filters(result, filters)
00732         return result

Here is the call graph for this function:

Here is the caller graph for this function:

def logging.config.DictConfigurator.configure_logger (   self,
  name,
  config,
  incremental = False 
)
Configure a non-root logger from a dictionary.

Definition at line 759 of file config.py.

00759 
00760     def configure_logger(self, name, config, incremental=False):
00761         """Configure a non-root logger from a dictionary."""
00762         logger = logging.getLogger(name)
00763         self.common_logger_config(logger, config, incremental)
00764         propagate = config.get('propagate', None)
00765         if propagate is not None:
00766             logger.propagate = propagate

Here is the call graph for this function:

Here is the caller graph for this function:

def logging.config.DictConfigurator.configure_root (   self,
  config,
  incremental = False 
)
Configure a root logger from a dictionary.

Definition at line 767 of file config.py.

00767 
00768     def configure_root(self, config, incremental=False):
00769         """Configure a root logger from a dictionary."""
00770         root = logging.getLogger()
00771         self.common_logger_config(root, config, incremental)

Here is the call graph for this function:

Here is the caller graph for this function:

def logging.config.BaseConfigurator.convert (   self,
  value 
) [inherited]
Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do.

Definition at line 443 of file config.py.

00443 
00444     def convert(self, value):
00445         """
00446         Convert values to an appropriate type. dicts, lists and tuples are
00447         replaced by their converting alternatives. Strings are checked to
00448         see if they have a conversion format and are converted if they do.
00449         """
00450         if not isinstance(value, ConvertingDict) and isinstance(value, dict):
00451             value = ConvertingDict(value)
00452             value.configurator = self
00453         elif not isinstance(value, ConvertingList) and isinstance(value, list):
00454             value = ConvertingList(value)
00455             value.configurator = self
00456         elif not isinstance(value, ConvertingTuple) and\
00457                  isinstance(value, tuple):
00458             value = ConvertingTuple(value)
00459             value.configurator = self
00460         elif isinstance(value, str): # str for py3k
00461             m = self.CONVERT_PATTERN.match(value)
00462             if m:
00463                 d = m.groupdict()
00464                 prefix = d['prefix']
00465                 converter = self.value_converters.get(prefix, None)
00466                 if converter:
00467                     suffix = d['suffix']
00468                     converter = getattr(self, converter)
00469                     value = converter(suffix)
00470         return value

Here is the call graph for this function:

def logging.config.BaseConfigurator.ext_convert (   self,
  value 
) [inherited]
Default converter for the ext:// protocol.

Definition at line 405 of file config.py.

00405 
00406     def ext_convert(self, value):
00407         """Default converter for the ext:// protocol."""
00408         return self.resolve(value)

Here is the call graph for this function:

def logging.config.BaseConfigurator.resolve (   self,
  s 
) [inherited]
Resolve strings to objects using standard import and attribute
syntax.

Definition at line 382 of file config.py.

00382 
00383     def resolve(self, s):
00384         """
00385         Resolve strings to objects using standard import and attribute
00386         syntax.
00387         """
00388         name = s.split('.')
00389         used = name.pop(0)
00390         try:
00391             found = self.importer(used)
00392             for frag in name:
00393                 used += '.' + frag
00394                 try:
00395                     found = getattr(found, frag)
00396                 except AttributeError:
00397                     self.importer(used)
00398                     found = getattr(found, frag)
00399             return found
00400         except ImportError:
00401             e, tb = sys.exc_info()[1:]
00402             v = ValueError('Cannot resolve %r: %s' % (s, e))
00403             v.__cause__, v.__traceback__ = e, tb
00404             raise v

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

Definition at line 379 of file config.py.

tuple logging.config.BaseConfigurator.CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$') [static, inherited]

Definition at line 363 of file config.py.

tuple logging.config.BaseConfigurator.DIGIT_PATTERN = re.compile(r'^\d+$') [static, inherited]

Definition at line 368 of file config.py.

tuple logging.config.BaseConfigurator.DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*') [static, inherited]

Definition at line 366 of file config.py.

tuple logging.config.BaseConfigurator.importer = staticmethod(__import__) [static, inherited]

Definition at line 376 of file config.py.

tuple logging.config.BaseConfigurator.INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*') [static, inherited]

Definition at line 367 of file config.py.

Definition at line 107 of file object.h.

struct _typeobject* _object::ob_type [inherited]

Definition at line 108 of file object.h.

dictionary logging.config.BaseConfigurator.value_converters [static, inherited]
Initial value:
{
        'ext' : 'ext_convert',
        'cfg' : 'cfg_convert',
    }

Definition at line 370 of file config.py.

tuple logging.config.BaseConfigurator.WORD_PATTERN = re.compile(r'^\s*(\w+)\s*') [static, inherited]

Definition at line 365 of file config.py.


The documentation for this class was generated from the following file: