jpayne@69: # Copyright 2001-2019 by Vinay Sajip. All Rights Reserved. jpayne@69: # jpayne@69: # Permission to use, copy, modify, and distribute this software and its jpayne@69: # documentation for any purpose and without fee is hereby granted, jpayne@69: # provided that the above copyright notice appear in all copies and that jpayne@69: # both that copyright notice and this permission notice appear in jpayne@69: # supporting documentation, and that the name of Vinay Sajip jpayne@69: # not be used in advertising or publicity pertaining to distribution jpayne@69: # of the software without specific, written prior permission. jpayne@69: # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING jpayne@69: # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL jpayne@69: # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR jpayne@69: # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER jpayne@69: # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT jpayne@69: # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. jpayne@69: jpayne@69: """ jpayne@69: Configuration functions for the logging package for Python. The core package jpayne@69: is based on PEP 282 and comments thereto in comp.lang.python, and influenced jpayne@69: by Apache's log4j system. jpayne@69: jpayne@69: Copyright (C) 2001-2019 Vinay Sajip. All Rights Reserved. jpayne@69: jpayne@69: To use, simply 'import logging' and log away! jpayne@69: """ jpayne@69: jpayne@69: import errno jpayne@69: import io jpayne@69: import logging jpayne@69: import logging.handlers jpayne@69: import re jpayne@69: import struct jpayne@69: import sys jpayne@69: import threading jpayne@69: import traceback jpayne@69: jpayne@69: from socketserver import ThreadingTCPServer, StreamRequestHandler jpayne@69: jpayne@69: jpayne@69: DEFAULT_LOGGING_CONFIG_PORT = 9030 jpayne@69: jpayne@69: RESET_ERROR = errno.ECONNRESET jpayne@69: jpayne@69: # jpayne@69: # The following code implements a socket listener for on-the-fly jpayne@69: # reconfiguration of logging. jpayne@69: # jpayne@69: # _listener holds the server object doing the listening jpayne@69: _listener = None jpayne@69: jpayne@69: def fileConfig(fname, defaults=None, disable_existing_loggers=True): jpayne@69: """ jpayne@69: Read the logging configuration from a ConfigParser-format file. jpayne@69: jpayne@69: This can be called several times from an application, allowing an end user jpayne@69: the ability to select from various pre-canned configurations (if the jpayne@69: developer provides a mechanism to present the choices and load the chosen jpayne@69: configuration). jpayne@69: """ jpayne@69: import configparser jpayne@69: jpayne@69: if isinstance(fname, configparser.RawConfigParser): jpayne@69: cp = fname jpayne@69: else: jpayne@69: cp = configparser.ConfigParser(defaults) jpayne@69: if hasattr(fname, 'readline'): jpayne@69: cp.read_file(fname) jpayne@69: else: jpayne@69: cp.read(fname) jpayne@69: jpayne@69: formatters = _create_formatters(cp) jpayne@69: jpayne@69: # critical section jpayne@69: logging._acquireLock() jpayne@69: try: jpayne@69: _clearExistingHandlers() jpayne@69: jpayne@69: # Handlers add themselves to logging._handlers jpayne@69: handlers = _install_handlers(cp, formatters) jpayne@69: _install_loggers(cp, handlers, disable_existing_loggers) jpayne@69: finally: jpayne@69: logging._releaseLock() jpayne@69: jpayne@69: jpayne@69: def _resolve(name): jpayne@69: """Resolve a dotted name to a global object.""" jpayne@69: name = name.split('.') jpayne@69: used = name.pop(0) jpayne@69: found = __import__(used) jpayne@69: for n in name: jpayne@69: used = used + '.' + n jpayne@69: try: jpayne@69: found = getattr(found, n) jpayne@69: except AttributeError: jpayne@69: __import__(used) jpayne@69: found = getattr(found, n) jpayne@69: return found jpayne@69: jpayne@69: def _strip_spaces(alist): jpayne@69: return map(str.strip, alist) jpayne@69: jpayne@69: def _create_formatters(cp): jpayne@69: """Create and return formatters""" jpayne@69: flist = cp["formatters"]["keys"] jpayne@69: if not len(flist): jpayne@69: return {} jpayne@69: flist = flist.split(",") jpayne@69: flist = _strip_spaces(flist) jpayne@69: formatters = {} jpayne@69: for form in flist: jpayne@69: sectname = "formatter_%s" % form jpayne@69: fs = cp.get(sectname, "format", raw=True, fallback=None) jpayne@69: dfs = cp.get(sectname, "datefmt", raw=True, fallback=None) jpayne@69: stl = cp.get(sectname, "style", raw=True, fallback='%') jpayne@69: c = logging.Formatter jpayne@69: class_name = cp[sectname].get("class") jpayne@69: if class_name: jpayne@69: c = _resolve(class_name) jpayne@69: f = c(fs, dfs, stl) jpayne@69: formatters[form] = f jpayne@69: return formatters jpayne@69: jpayne@69: jpayne@69: def _install_handlers(cp, formatters): jpayne@69: """Install and return handlers""" jpayne@69: hlist = cp["handlers"]["keys"] jpayne@69: if not len(hlist): jpayne@69: return {} jpayne@69: hlist = hlist.split(",") jpayne@69: hlist = _strip_spaces(hlist) jpayne@69: handlers = {} jpayne@69: fixups = [] #for inter-handler references jpayne@69: for hand in hlist: jpayne@69: section = cp["handler_%s" % hand] jpayne@69: klass = section["class"] jpayne@69: fmt = section.get("formatter", "") jpayne@69: try: jpayne@69: klass = eval(klass, vars(logging)) jpayne@69: except (AttributeError, NameError): jpayne@69: klass = _resolve(klass) jpayne@69: args = section.get("args", '()') jpayne@69: args = eval(args, vars(logging)) jpayne@69: kwargs = section.get("kwargs", '{}') jpayne@69: kwargs = eval(kwargs, vars(logging)) jpayne@69: h = klass(*args, **kwargs) jpayne@69: if "level" in section: jpayne@69: level = section["level"] jpayne@69: h.setLevel(level) jpayne@69: if len(fmt): jpayne@69: h.setFormatter(formatters[fmt]) jpayne@69: if issubclass(klass, logging.handlers.MemoryHandler): jpayne@69: target = section.get("target", "") jpayne@69: if len(target): #the target handler may not be loaded yet, so keep for later... jpayne@69: fixups.append((h, target)) jpayne@69: handlers[hand] = h jpayne@69: #now all handlers are loaded, fixup inter-handler references... jpayne@69: for h, t in fixups: jpayne@69: h.setTarget(handlers[t]) jpayne@69: return handlers jpayne@69: jpayne@69: def _handle_existing_loggers(existing, child_loggers, disable_existing): jpayne@69: """ jpayne@69: When (re)configuring logging, handle loggers which were in the previous jpayne@69: configuration but are not in the new configuration. There's no point jpayne@69: deleting them as other threads may continue to hold references to them; jpayne@69: and by disabling them, you stop them doing any logging. jpayne@69: jpayne@69: However, don't disable children of named loggers, as that's probably not jpayne@69: what was intended by the user. Also, allow existing loggers to NOT be jpayne@69: disabled if disable_existing is false. jpayne@69: """ jpayne@69: root = logging.root jpayne@69: for log in existing: jpayne@69: logger = root.manager.loggerDict[log] jpayne@69: if log in child_loggers: jpayne@69: if not isinstance(logger, logging.PlaceHolder): jpayne@69: logger.setLevel(logging.NOTSET) jpayne@69: logger.handlers = [] jpayne@69: logger.propagate = True jpayne@69: else: jpayne@69: logger.disabled = disable_existing jpayne@69: jpayne@69: def _install_loggers(cp, handlers, disable_existing): jpayne@69: """Create and install loggers""" jpayne@69: jpayne@69: # configure the root first jpayne@69: llist = cp["loggers"]["keys"] jpayne@69: llist = llist.split(",") jpayne@69: llist = list(_strip_spaces(llist)) jpayne@69: llist.remove("root") jpayne@69: section = cp["logger_root"] jpayne@69: root = logging.root jpayne@69: log = root jpayne@69: if "level" in section: jpayne@69: level = section["level"] jpayne@69: log.setLevel(level) jpayne@69: for h in root.handlers[:]: jpayne@69: root.removeHandler(h) jpayne@69: hlist = section["handlers"] jpayne@69: if len(hlist): jpayne@69: hlist = hlist.split(",") jpayne@69: hlist = _strip_spaces(hlist) jpayne@69: for hand in hlist: jpayne@69: log.addHandler(handlers[hand]) jpayne@69: jpayne@69: #and now the others... jpayne@69: #we don't want to lose the existing loggers, jpayne@69: #since other threads may have pointers to them. jpayne@69: #existing is set to contain all existing loggers, jpayne@69: #and as we go through the new configuration we jpayne@69: #remove any which are configured. At the end, jpayne@69: #what's left in existing is the set of loggers jpayne@69: #which were in the previous configuration but jpayne@69: #which are not in the new configuration. jpayne@69: existing = list(root.manager.loggerDict.keys()) jpayne@69: #The list needs to be sorted so that we can jpayne@69: #avoid disabling child loggers of explicitly jpayne@69: #named loggers. With a sorted list it is easier jpayne@69: #to find the child loggers. jpayne@69: existing.sort() jpayne@69: #We'll keep the list of existing loggers jpayne@69: #which are children of named loggers here... jpayne@69: child_loggers = [] jpayne@69: #now set up the new ones... jpayne@69: for log in llist: jpayne@69: section = cp["logger_%s" % log] jpayne@69: qn = section["qualname"] jpayne@69: propagate = section.getint("propagate", fallback=1) jpayne@69: logger = logging.getLogger(qn) jpayne@69: if qn in existing: jpayne@69: i = existing.index(qn) + 1 # start with the entry after qn jpayne@69: prefixed = qn + "." jpayne@69: pflen = len(prefixed) jpayne@69: num_existing = len(existing) jpayne@69: while i < num_existing: jpayne@69: if existing[i][:pflen] == prefixed: jpayne@69: child_loggers.append(existing[i]) jpayne@69: i += 1 jpayne@69: existing.remove(qn) jpayne@69: if "level" in section: jpayne@69: level = section["level"] jpayne@69: logger.setLevel(level) jpayne@69: for h in logger.handlers[:]: jpayne@69: logger.removeHandler(h) jpayne@69: logger.propagate = propagate jpayne@69: logger.disabled = 0 jpayne@69: hlist = section["handlers"] jpayne@69: if len(hlist): jpayne@69: hlist = hlist.split(",") jpayne@69: hlist = _strip_spaces(hlist) jpayne@69: for hand in hlist: jpayne@69: logger.addHandler(handlers[hand]) jpayne@69: jpayne@69: #Disable any old loggers. There's no point deleting jpayne@69: #them as other threads may continue to hold references jpayne@69: #and by disabling them, you stop them doing any logging. jpayne@69: #However, don't disable children of named loggers, as that's jpayne@69: #probably not what was intended by the user. jpayne@69: #for log in existing: jpayne@69: # logger = root.manager.loggerDict[log] jpayne@69: # if log in child_loggers: jpayne@69: # logger.level = logging.NOTSET jpayne@69: # logger.handlers = [] jpayne@69: # logger.propagate = 1 jpayne@69: # elif disable_existing_loggers: jpayne@69: # logger.disabled = 1 jpayne@69: _handle_existing_loggers(existing, child_loggers, disable_existing) jpayne@69: jpayne@69: jpayne@69: def _clearExistingHandlers(): jpayne@69: """Clear and close existing handlers""" jpayne@69: logging._handlers.clear() jpayne@69: logging.shutdown(logging._handlerList[:]) jpayne@69: del logging._handlerList[:] jpayne@69: jpayne@69: jpayne@69: IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I) jpayne@69: jpayne@69: jpayne@69: def valid_ident(s): jpayne@69: m = IDENTIFIER.match(s) jpayne@69: if not m: jpayne@69: raise ValueError('Not a valid Python identifier: %r' % s) jpayne@69: return True jpayne@69: jpayne@69: jpayne@69: class ConvertingMixin(object): jpayne@69: """For ConvertingXXX's, this mixin class provides common functions""" jpayne@69: jpayne@69: def convert_with_key(self, key, value, replace=True): jpayne@69: result = self.configurator.convert(value) jpayne@69: #If the converted value is different, save for next time jpayne@69: if value is not result: jpayne@69: if replace: jpayne@69: self[key] = result jpayne@69: if type(result) in (ConvertingDict, ConvertingList, jpayne@69: ConvertingTuple): jpayne@69: result.parent = self jpayne@69: result.key = key jpayne@69: return result jpayne@69: jpayne@69: def convert(self, value): jpayne@69: result = self.configurator.convert(value) jpayne@69: if value is not result: jpayne@69: if type(result) in (ConvertingDict, ConvertingList, jpayne@69: ConvertingTuple): jpayne@69: result.parent = self jpayne@69: return result jpayne@69: jpayne@69: jpayne@69: # The ConvertingXXX classes are wrappers around standard Python containers, jpayne@69: # and they serve to convert any suitable values in the container. The jpayne@69: # conversion converts base dicts, lists and tuples to their wrapped jpayne@69: # equivalents, whereas strings which match a conversion format are converted jpayne@69: # appropriately. jpayne@69: # jpayne@69: # Each wrapper should have a configurator attribute holding the actual jpayne@69: # configurator to use for conversion. jpayne@69: jpayne@69: class ConvertingDict(dict, ConvertingMixin): jpayne@69: """A converting dictionary wrapper.""" jpayne@69: jpayne@69: def __getitem__(self, key): jpayne@69: value = dict.__getitem__(self, key) jpayne@69: return self.convert_with_key(key, value) jpayne@69: jpayne@69: def get(self, key, default=None): jpayne@69: value = dict.get(self, key, default) jpayne@69: return self.convert_with_key(key, value) jpayne@69: jpayne@69: def pop(self, key, default=None): jpayne@69: value = dict.pop(self, key, default) jpayne@69: return self.convert_with_key(key, value, replace=False) jpayne@69: jpayne@69: class ConvertingList(list, ConvertingMixin): jpayne@69: """A converting list wrapper.""" jpayne@69: def __getitem__(self, key): jpayne@69: value = list.__getitem__(self, key) jpayne@69: return self.convert_with_key(key, value) jpayne@69: jpayne@69: def pop(self, idx=-1): jpayne@69: value = list.pop(self, idx) jpayne@69: return self.convert(value) jpayne@69: jpayne@69: class ConvertingTuple(tuple, ConvertingMixin): jpayne@69: """A converting tuple wrapper.""" jpayne@69: def __getitem__(self, key): jpayne@69: value = tuple.__getitem__(self, key) jpayne@69: # Can't replace a tuple entry. jpayne@69: return self.convert_with_key(key, value, replace=False) jpayne@69: jpayne@69: class BaseConfigurator(object): jpayne@69: """ jpayne@69: The configurator base class which defines some useful defaults. jpayne@69: """ jpayne@69: jpayne@69: CONVERT_PATTERN = re.compile(r'^(?P[a-z]+)://(?P.*)$') jpayne@69: jpayne@69: WORD_PATTERN = re.compile(r'^\s*(\w+)\s*') jpayne@69: DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*') jpayne@69: INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*') jpayne@69: DIGIT_PATTERN = re.compile(r'^\d+$') jpayne@69: jpayne@69: value_converters = { jpayne@69: 'ext' : 'ext_convert', jpayne@69: 'cfg' : 'cfg_convert', jpayne@69: } jpayne@69: jpayne@69: # We might want to use a different one, e.g. importlib jpayne@69: importer = staticmethod(__import__) jpayne@69: jpayne@69: def __init__(self, config): jpayne@69: self.config = ConvertingDict(config) jpayne@69: self.config.configurator = self jpayne@69: jpayne@69: def resolve(self, s): jpayne@69: """ jpayne@69: Resolve strings to objects using standard import and attribute jpayne@69: syntax. jpayne@69: """ jpayne@69: name = s.split('.') jpayne@69: used = name.pop(0) jpayne@69: try: jpayne@69: found = self.importer(used) jpayne@69: for frag in name: jpayne@69: used += '.' + frag jpayne@69: try: jpayne@69: found = getattr(found, frag) jpayne@69: except AttributeError: jpayne@69: self.importer(used) jpayne@69: found = getattr(found, frag) jpayne@69: return found jpayne@69: except ImportError: jpayne@69: e, tb = sys.exc_info()[1:] jpayne@69: v = ValueError('Cannot resolve %r: %s' % (s, e)) jpayne@69: v.__cause__, v.__traceback__ = e, tb jpayne@69: raise v jpayne@69: jpayne@69: def ext_convert(self, value): jpayne@69: """Default converter for the ext:// protocol.""" jpayne@69: return self.resolve(value) jpayne@69: jpayne@69: def cfg_convert(self, value): jpayne@69: """Default converter for the cfg:// protocol.""" jpayne@69: rest = value jpayne@69: m = self.WORD_PATTERN.match(rest) jpayne@69: if m is None: jpayne@69: raise ValueError("Unable to convert %r" % value) jpayne@69: else: jpayne@69: rest = rest[m.end():] jpayne@69: d = self.config[m.groups()[0]] jpayne@69: #print d, rest jpayne@69: while rest: jpayne@69: m = self.DOT_PATTERN.match(rest) jpayne@69: if m: jpayne@69: d = d[m.groups()[0]] jpayne@69: else: jpayne@69: m = self.INDEX_PATTERN.match(rest) jpayne@69: if m: jpayne@69: idx = m.groups()[0] jpayne@69: if not self.DIGIT_PATTERN.match(idx): jpayne@69: d = d[idx] jpayne@69: else: jpayne@69: try: jpayne@69: n = int(idx) # try as number first (most likely) jpayne@69: d = d[n] jpayne@69: except TypeError: jpayne@69: d = d[idx] jpayne@69: if m: jpayne@69: rest = rest[m.end():] jpayne@69: else: jpayne@69: raise ValueError('Unable to convert ' jpayne@69: '%r at %r' % (value, rest)) jpayne@69: #rest should be empty jpayne@69: return d jpayne@69: jpayne@69: def convert(self, value): jpayne@69: """ jpayne@69: Convert values to an appropriate type. dicts, lists and tuples are jpayne@69: replaced by their converting alternatives. Strings are checked to jpayne@69: see if they have a conversion format and are converted if they do. jpayne@69: """ jpayne@69: if not isinstance(value, ConvertingDict) and isinstance(value, dict): jpayne@69: value = ConvertingDict(value) jpayne@69: value.configurator = self jpayne@69: elif not isinstance(value, ConvertingList) and isinstance(value, list): jpayne@69: value = ConvertingList(value) jpayne@69: value.configurator = self jpayne@69: elif not isinstance(value, ConvertingTuple) and\ jpayne@69: isinstance(value, tuple): jpayne@69: value = ConvertingTuple(value) jpayne@69: value.configurator = self jpayne@69: elif isinstance(value, str): # str for py3k jpayne@69: m = self.CONVERT_PATTERN.match(value) jpayne@69: if m: jpayne@69: d = m.groupdict() jpayne@69: prefix = d['prefix'] jpayne@69: converter = self.value_converters.get(prefix, None) jpayne@69: if converter: jpayne@69: suffix = d['suffix'] jpayne@69: converter = getattr(self, converter) jpayne@69: value = converter(suffix) jpayne@69: return value jpayne@69: jpayne@69: def configure_custom(self, config): jpayne@69: """Configure an object with a user-supplied factory.""" jpayne@69: c = config.pop('()') jpayne@69: if not callable(c): jpayne@69: c = self.resolve(c) jpayne@69: props = config.pop('.', None) jpayne@69: # Check for valid identifiers jpayne@69: kwargs = {k: config[k] for k in config if valid_ident(k)} jpayne@69: result = c(**kwargs) jpayne@69: if props: jpayne@69: for name, value in props.items(): jpayne@69: setattr(result, name, value) jpayne@69: return result jpayne@69: jpayne@69: def as_tuple(self, value): jpayne@69: """Utility function which converts lists to tuples.""" jpayne@69: if isinstance(value, list): jpayne@69: value = tuple(value) jpayne@69: return value jpayne@69: jpayne@69: class DictConfigurator(BaseConfigurator): jpayne@69: """ jpayne@69: Configure logging using a dictionary-like object to describe the jpayne@69: configuration. jpayne@69: """ jpayne@69: jpayne@69: def configure(self): jpayne@69: """Do the configuration.""" jpayne@69: jpayne@69: config = self.config jpayne@69: if 'version' not in config: jpayne@69: raise ValueError("dictionary doesn't specify a version") jpayne@69: if config['version'] != 1: jpayne@69: raise ValueError("Unsupported version: %s" % config['version']) jpayne@69: incremental = config.pop('incremental', False) jpayne@69: EMPTY_DICT = {} jpayne@69: logging._acquireLock() jpayne@69: try: jpayne@69: if incremental: jpayne@69: handlers = config.get('handlers', EMPTY_DICT) jpayne@69: for name in handlers: jpayne@69: if name not in logging._handlers: jpayne@69: raise ValueError('No handler found with ' jpayne@69: 'name %r' % name) jpayne@69: else: jpayne@69: try: jpayne@69: handler = logging._handlers[name] jpayne@69: handler_config = handlers[name] jpayne@69: level = handler_config.get('level', None) jpayne@69: if level: jpayne@69: handler.setLevel(logging._checkLevel(level)) jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to configure handler ' jpayne@69: '%r' % name) from e jpayne@69: loggers = config.get('loggers', EMPTY_DICT) jpayne@69: for name in loggers: jpayne@69: try: jpayne@69: self.configure_logger(name, loggers[name], True) jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to configure logger ' jpayne@69: '%r' % name) from e jpayne@69: root = config.get('root', None) jpayne@69: if root: jpayne@69: try: jpayne@69: self.configure_root(root, True) jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to configure root ' jpayne@69: 'logger') from e jpayne@69: else: jpayne@69: disable_existing = config.pop('disable_existing_loggers', True) jpayne@69: jpayne@69: _clearExistingHandlers() jpayne@69: jpayne@69: # Do formatters first - they don't refer to anything else jpayne@69: formatters = config.get('formatters', EMPTY_DICT) jpayne@69: for name in formatters: jpayne@69: try: jpayne@69: formatters[name] = self.configure_formatter( jpayne@69: formatters[name]) jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to configure ' jpayne@69: 'formatter %r' % name) from e jpayne@69: # Next, do filters - they don't refer to anything else, either jpayne@69: filters = config.get('filters', EMPTY_DICT) jpayne@69: for name in filters: jpayne@69: try: jpayne@69: filters[name] = self.configure_filter(filters[name]) jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to configure ' jpayne@69: 'filter %r' % name) from e jpayne@69: jpayne@69: # Next, do handlers - they refer to formatters and filters jpayne@69: # As handlers can refer to other handlers, sort the keys jpayne@69: # to allow a deterministic order of configuration jpayne@69: handlers = config.get('handlers', EMPTY_DICT) jpayne@69: deferred = [] jpayne@69: for name in sorted(handlers): jpayne@69: try: jpayne@69: handler = self.configure_handler(handlers[name]) jpayne@69: handler.name = name jpayne@69: handlers[name] = handler jpayne@69: except Exception as e: jpayne@69: if 'target not configured yet' in str(e.__cause__): jpayne@69: deferred.append(name) jpayne@69: else: jpayne@69: raise ValueError('Unable to configure handler ' jpayne@69: '%r' % name) from e jpayne@69: jpayne@69: # Now do any that were deferred jpayne@69: for name in deferred: jpayne@69: try: jpayne@69: handler = self.configure_handler(handlers[name]) jpayne@69: handler.name = name jpayne@69: handlers[name] = handler jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to configure handler ' jpayne@69: '%r' % name) from e jpayne@69: jpayne@69: # Next, do loggers - they refer to handlers and filters jpayne@69: jpayne@69: #we don't want to lose the existing loggers, jpayne@69: #since other threads may have pointers to them. jpayne@69: #existing is set to contain all existing loggers, jpayne@69: #and as we go through the new configuration we jpayne@69: #remove any which are configured. At the end, jpayne@69: #what's left in existing is the set of loggers jpayne@69: #which were in the previous configuration but jpayne@69: #which are not in the new configuration. jpayne@69: root = logging.root jpayne@69: existing = list(root.manager.loggerDict.keys()) jpayne@69: #The list needs to be sorted so that we can jpayne@69: #avoid disabling child loggers of explicitly jpayne@69: #named loggers. With a sorted list it is easier jpayne@69: #to find the child loggers. jpayne@69: existing.sort() jpayne@69: #We'll keep the list of existing loggers jpayne@69: #which are children of named loggers here... jpayne@69: child_loggers = [] jpayne@69: #now set up the new ones... jpayne@69: loggers = config.get('loggers', EMPTY_DICT) jpayne@69: for name in loggers: jpayne@69: if name in existing: jpayne@69: i = existing.index(name) + 1 # look after name jpayne@69: prefixed = name + "." jpayne@69: pflen = len(prefixed) jpayne@69: num_existing = len(existing) jpayne@69: while i < num_existing: jpayne@69: if existing[i][:pflen] == prefixed: jpayne@69: child_loggers.append(existing[i]) jpayne@69: i += 1 jpayne@69: existing.remove(name) jpayne@69: try: jpayne@69: self.configure_logger(name, loggers[name]) jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to configure logger ' jpayne@69: '%r' % name) from e jpayne@69: jpayne@69: #Disable any old loggers. There's no point deleting jpayne@69: #them as other threads may continue to hold references jpayne@69: #and by disabling them, you stop them doing any logging. jpayne@69: #However, don't disable children of named loggers, as that's jpayne@69: #probably not what was intended by the user. jpayne@69: #for log in existing: jpayne@69: # logger = root.manager.loggerDict[log] jpayne@69: # if log in child_loggers: jpayne@69: # logger.level = logging.NOTSET jpayne@69: # logger.handlers = [] jpayne@69: # logger.propagate = True jpayne@69: # elif disable_existing: jpayne@69: # logger.disabled = True jpayne@69: _handle_existing_loggers(existing, child_loggers, jpayne@69: disable_existing) jpayne@69: jpayne@69: # And finally, do the root logger jpayne@69: root = config.get('root', None) jpayne@69: if root: jpayne@69: try: jpayne@69: self.configure_root(root) jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to configure root ' jpayne@69: 'logger') from e jpayne@69: finally: jpayne@69: logging._releaseLock() jpayne@69: jpayne@69: def configure_formatter(self, config): jpayne@69: """Configure a formatter from a dictionary.""" jpayne@69: if '()' in config: jpayne@69: factory = config['()'] # for use in exception handler jpayne@69: try: jpayne@69: result = self.configure_custom(config) jpayne@69: except TypeError as te: jpayne@69: if "'format'" not in str(te): jpayne@69: raise jpayne@69: #Name of parameter changed from fmt to format. jpayne@69: #Retry with old name. jpayne@69: #This is so that code can be used with older Python versions jpayne@69: #(e.g. by Django) jpayne@69: config['fmt'] = config.pop('format') jpayne@69: config['()'] = factory jpayne@69: result = self.configure_custom(config) jpayne@69: else: jpayne@69: fmt = config.get('format', None) jpayne@69: dfmt = config.get('datefmt', None) jpayne@69: style = config.get('style', '%') jpayne@69: cname = config.get('class', None) jpayne@69: jpayne@69: if not cname: jpayne@69: c = logging.Formatter jpayne@69: else: jpayne@69: c = _resolve(cname) jpayne@69: jpayne@69: # A TypeError would be raised if "validate" key is passed in with a formatter callable jpayne@69: # that does not accept "validate" as a parameter jpayne@69: if 'validate' in config: # if user hasn't mentioned it, the default will be fine jpayne@69: result = c(fmt, dfmt, style, config['validate']) jpayne@69: else: jpayne@69: result = c(fmt, dfmt, style) jpayne@69: jpayne@69: return result jpayne@69: jpayne@69: def configure_filter(self, config): jpayne@69: """Configure a filter from a dictionary.""" jpayne@69: if '()' in config: jpayne@69: result = self.configure_custom(config) jpayne@69: else: jpayne@69: name = config.get('name', '') jpayne@69: result = logging.Filter(name) jpayne@69: return result jpayne@69: jpayne@69: def add_filters(self, filterer, filters): jpayne@69: """Add filters to a filterer from a list of names.""" jpayne@69: for f in filters: jpayne@69: try: jpayne@69: filterer.addFilter(self.config['filters'][f]) jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to add filter %r' % f) from e jpayne@69: jpayne@69: def configure_handler(self, config): jpayne@69: """Configure a handler from a dictionary.""" jpayne@69: config_copy = dict(config) # for restoring in case of error jpayne@69: formatter = config.pop('formatter', None) jpayne@69: if formatter: jpayne@69: try: jpayne@69: formatter = self.config['formatters'][formatter] jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to set formatter ' jpayne@69: '%r' % formatter) from e jpayne@69: level = config.pop('level', None) jpayne@69: filters = config.pop('filters', None) jpayne@69: if '()' in config: jpayne@69: c = config.pop('()') jpayne@69: if not callable(c): jpayne@69: c = self.resolve(c) jpayne@69: factory = c jpayne@69: else: jpayne@69: cname = config.pop('class') jpayne@69: klass = self.resolve(cname) jpayne@69: #Special case for handler which refers to another handler jpayne@69: if issubclass(klass, logging.handlers.MemoryHandler) and\ jpayne@69: 'target' in config: jpayne@69: try: jpayne@69: th = self.config['handlers'][config['target']] jpayne@69: if not isinstance(th, logging.Handler): jpayne@69: config.update(config_copy) # restore for deferred cfg jpayne@69: raise TypeError('target not configured yet') jpayne@69: config['target'] = th jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to set target handler ' jpayne@69: '%r' % config['target']) from e jpayne@69: elif issubclass(klass, logging.handlers.SMTPHandler) and\ jpayne@69: 'mailhost' in config: jpayne@69: config['mailhost'] = self.as_tuple(config['mailhost']) jpayne@69: elif issubclass(klass, logging.handlers.SysLogHandler) and\ jpayne@69: 'address' in config: jpayne@69: config['address'] = self.as_tuple(config['address']) jpayne@69: factory = klass jpayne@69: props = config.pop('.', None) jpayne@69: kwargs = {k: config[k] for k in config if valid_ident(k)} jpayne@69: try: jpayne@69: result = factory(**kwargs) jpayne@69: except TypeError as te: jpayne@69: if "'stream'" not in str(te): jpayne@69: raise jpayne@69: #The argument name changed from strm to stream jpayne@69: #Retry with old name. jpayne@69: #This is so that code can be used with older Python versions jpayne@69: #(e.g. by Django) jpayne@69: kwargs['strm'] = kwargs.pop('stream') jpayne@69: result = factory(**kwargs) jpayne@69: if formatter: jpayne@69: result.setFormatter(formatter) jpayne@69: if level is not None: jpayne@69: result.setLevel(logging._checkLevel(level)) jpayne@69: if filters: jpayne@69: self.add_filters(result, filters) jpayne@69: if props: jpayne@69: for name, value in props.items(): jpayne@69: setattr(result, name, value) jpayne@69: return result jpayne@69: jpayne@69: def add_handlers(self, logger, handlers): jpayne@69: """Add handlers to a logger from a list of names.""" jpayne@69: for h in handlers: jpayne@69: try: jpayne@69: logger.addHandler(self.config['handlers'][h]) jpayne@69: except Exception as e: jpayne@69: raise ValueError('Unable to add handler %r' % h) from e jpayne@69: jpayne@69: def common_logger_config(self, logger, config, incremental=False): jpayne@69: """ jpayne@69: Perform configuration which is common to root and non-root loggers. jpayne@69: """ jpayne@69: level = config.get('level', None) jpayne@69: if level is not None: jpayne@69: logger.setLevel(logging._checkLevel(level)) jpayne@69: if not incremental: jpayne@69: #Remove any existing handlers jpayne@69: for h in logger.handlers[:]: jpayne@69: logger.removeHandler(h) jpayne@69: handlers = config.get('handlers', None) jpayne@69: if handlers: jpayne@69: self.add_handlers(logger, handlers) jpayne@69: filters = config.get('filters', None) jpayne@69: if filters: jpayne@69: self.add_filters(logger, filters) jpayne@69: jpayne@69: def configure_logger(self, name, config, incremental=False): jpayne@69: """Configure a non-root logger from a dictionary.""" jpayne@69: logger = logging.getLogger(name) jpayne@69: self.common_logger_config(logger, config, incremental) jpayne@69: propagate = config.get('propagate', None) jpayne@69: if propagate is not None: jpayne@69: logger.propagate = propagate jpayne@69: jpayne@69: def configure_root(self, config, incremental=False): jpayne@69: """Configure a root logger from a dictionary.""" jpayne@69: root = logging.getLogger() jpayne@69: self.common_logger_config(root, config, incremental) jpayne@69: jpayne@69: dictConfigClass = DictConfigurator jpayne@69: jpayne@69: def dictConfig(config): jpayne@69: """Configure logging using a dictionary.""" jpayne@69: dictConfigClass(config).configure() jpayne@69: jpayne@69: jpayne@69: def listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None): jpayne@69: """ jpayne@69: Start up a socket server on the specified port, and listen for new jpayne@69: configurations. jpayne@69: jpayne@69: These will be sent as a file suitable for processing by fileConfig(). jpayne@69: Returns a Thread object on which you can call start() to start the server, jpayne@69: and which you can join() when appropriate. To stop the server, call jpayne@69: stopListening(). jpayne@69: jpayne@69: Use the ``verify`` argument to verify any bytes received across the wire jpayne@69: from a client. If specified, it should be a callable which receives a jpayne@69: single argument - the bytes of configuration data received across the jpayne@69: network - and it should return either ``None``, to indicate that the jpayne@69: passed in bytes could not be verified and should be discarded, or a jpayne@69: byte string which is then passed to the configuration machinery as jpayne@69: normal. Note that you can return transformed bytes, e.g. by decrypting jpayne@69: the bytes passed in. jpayne@69: """ jpayne@69: jpayne@69: class ConfigStreamHandler(StreamRequestHandler): jpayne@69: """ jpayne@69: Handler for a logging configuration request. jpayne@69: jpayne@69: It expects a completely new logging configuration and uses fileConfig jpayne@69: to install it. jpayne@69: """ jpayne@69: def handle(self): jpayne@69: """ jpayne@69: Handle a request. jpayne@69: jpayne@69: Each request is expected to be a 4-byte length, packed using jpayne@69: struct.pack(">L", n), followed by the config file. jpayne@69: Uses fileConfig() to do the grunt work. jpayne@69: """ jpayne@69: try: jpayne@69: conn = self.connection jpayne@69: chunk = conn.recv(4) jpayne@69: if len(chunk) == 4: jpayne@69: slen = struct.unpack(">L", chunk)[0] jpayne@69: chunk = self.connection.recv(slen) jpayne@69: while len(chunk) < slen: jpayne@69: chunk = chunk + conn.recv(slen - len(chunk)) jpayne@69: if self.server.verify is not None: jpayne@69: chunk = self.server.verify(chunk) jpayne@69: if chunk is not None: # verified, can process jpayne@69: chunk = chunk.decode("utf-8") jpayne@69: try: jpayne@69: import json jpayne@69: d =json.loads(chunk) jpayne@69: assert isinstance(d, dict) jpayne@69: dictConfig(d) jpayne@69: except Exception: jpayne@69: #Apply new configuration. jpayne@69: jpayne@69: file = io.StringIO(chunk) jpayne@69: try: jpayne@69: fileConfig(file) jpayne@69: except Exception: jpayne@69: traceback.print_exc() jpayne@69: if self.server.ready: jpayne@69: self.server.ready.set() jpayne@69: except OSError as e: jpayne@69: if e.errno != RESET_ERROR: jpayne@69: raise jpayne@69: jpayne@69: class ConfigSocketReceiver(ThreadingTCPServer): jpayne@69: """ jpayne@69: A simple TCP socket-based logging config receiver. jpayne@69: """ jpayne@69: jpayne@69: allow_reuse_address = 1 jpayne@69: jpayne@69: def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT, jpayne@69: handler=None, ready=None, verify=None): jpayne@69: ThreadingTCPServer.__init__(self, (host, port), handler) jpayne@69: logging._acquireLock() jpayne@69: self.abort = 0 jpayne@69: logging._releaseLock() jpayne@69: self.timeout = 1 jpayne@69: self.ready = ready jpayne@69: self.verify = verify jpayne@69: jpayne@69: def serve_until_stopped(self): jpayne@69: import select jpayne@69: abort = 0 jpayne@69: while not abort: jpayne@69: rd, wr, ex = select.select([self.socket.fileno()], jpayne@69: [], [], jpayne@69: self.timeout) jpayne@69: if rd: jpayne@69: self.handle_request() jpayne@69: logging._acquireLock() jpayne@69: abort = self.abort jpayne@69: logging._releaseLock() jpayne@69: self.server_close() jpayne@69: jpayne@69: class Server(threading.Thread): jpayne@69: jpayne@69: def __init__(self, rcvr, hdlr, port, verify): jpayne@69: super(Server, self).__init__() jpayne@69: self.rcvr = rcvr jpayne@69: self.hdlr = hdlr jpayne@69: self.port = port jpayne@69: self.verify = verify jpayne@69: self.ready = threading.Event() jpayne@69: jpayne@69: def run(self): jpayne@69: server = self.rcvr(port=self.port, handler=self.hdlr, jpayne@69: ready=self.ready, jpayne@69: verify=self.verify) jpayne@69: if self.port == 0: jpayne@69: self.port = server.server_address[1] jpayne@69: self.ready.set() jpayne@69: global _listener jpayne@69: logging._acquireLock() jpayne@69: _listener = server jpayne@69: logging._releaseLock() jpayne@69: server.serve_until_stopped() jpayne@69: jpayne@69: return Server(ConfigSocketReceiver, ConfigStreamHandler, port, verify) jpayne@69: jpayne@69: def stopListening(): jpayne@69: """ jpayne@69: Stop the listening server which was created with a call to listen(). jpayne@69: """ jpayne@69: global _listener jpayne@69: logging._acquireLock() jpayne@69: try: jpayne@69: if _listener: jpayne@69: _listener.abort = 1 jpayne@69: _listener = None jpayne@69: finally: jpayne@69: logging._releaseLock()