| 1 | # This is a copy of the Python logging.config.dictconfig module, |
| 2 | # reproduced with permission. It is provided here for backwards |
| 3 | # compatibility for Python versions prior to 2.7. |
| 4 | # |
| 5 | # Copyright 2009-2010 by Vinay Sajip. All Rights Reserved. |
| 6 | # |
| 7 | # Permission to use, copy, modify, and distribute this software and its |
| 8 | # documentation for any purpose and without fee is hereby granted, |
| 9 | # provided that the above copyright notice appear in all copies and that |
| 10 | # both that copyright notice and this permission notice appear in |
| 11 | # supporting documentation, and that the name of Vinay Sajip |
| 12 | # not be used in advertising or publicity pertaining to distribution |
| 13 | # of the software without specific, written prior permission. |
| 14 | # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING |
| 15 | # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL |
| 16 | # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR |
| 17 | # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER |
| 18 | # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT |
| 19 | # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 20 | |
| 21 | import logging.handlers |
| 22 | import re |
| 23 | import sys |
| 24 | import types |
| 25 | |
| 26 | IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I) |
| 27 | |
| 28 | def valid_ident(s): |
| 29 | m = IDENTIFIER.match(s) |
| 30 | if not m: |
| 31 | raise ValueError('Not a valid Python identifier: %r' % s) |
| 32 | return True |
| 33 | |
| 34 | # |
| 35 | # This function is defined in logging only in recent versions of Python |
| 36 | # |
| 37 | try: |
| 38 | from logging import _checkLevel |
| 39 | except ImportError: |
| 40 | def _checkLevel(level): |
| 41 | if isinstance(level, int): |
| 42 | rv = level |
| 43 | elif str(level) == level: |
| 44 | if level not in logging._levelNames: |
| 45 | raise ValueError('Unknown level: %r' % level) |
| 46 | rv = logging._levelNames[level] |
| 47 | else: |
| 48 | raise TypeError('Level not an integer or a ' |
| 49 | 'valid string: %r' % level) |
| 50 | return rv |
| 51 | |
| 52 | # The ConvertingXXX classes are wrappers around standard Python containers, |
| 53 | # and they serve to convert any suitable values in the container. The |
| 54 | # conversion converts base dicts, lists and tuples to their wrapped |
| 55 | # equivalents, whereas strings which match a conversion format are converted |
| 56 | # appropriately. |
| 57 | # |
| 58 | # Each wrapper should have a configurator attribute holding the actual |
| 59 | # configurator to use for conversion. |
| 60 | |
| 61 | class ConvertingDict(dict): |
| 62 | """A converting dictionary wrapper.""" |
| 63 | |
| 64 | def __getitem__(self, key): |
| 65 | value = dict.__getitem__(self, key) |
| 66 | result = self.configurator.convert(value) |
| 67 | #If the converted value is different, save for next time |
| 68 | if value is not result: |
| 69 | self[key] = result |
| 70 | if type(result) in (ConvertingDict, ConvertingList, |
| 71 | ConvertingTuple): |
| 72 | result.parent = self |
| 73 | result.key = key |
| 74 | return result |
| 75 | |
| 76 | def get(self, key, default=None): |
| 77 | value = dict.get(self, key, default) |
| 78 | result = self.configurator.convert(value) |
| 79 | #If the converted value is different, save for next time |
| 80 | if value is not result: |
| 81 | self[key] = result |
| 82 | if type(result) in (ConvertingDict, ConvertingList, |
| 83 | ConvertingTuple): |
| 84 | result.parent = self |
| 85 | result.key = key |
| 86 | return result |
| 87 | |
| 88 | def pop(self, key, default=None): |
| 89 | value = dict.pop(self, key, default) |
| 90 | result = self.configurator.convert(value) |
| 91 | if value is not result: |
| 92 | if type(result) in (ConvertingDict, ConvertingList, |
| 93 | ConvertingTuple): |
| 94 | result.parent = self |
| 95 | result.key = key |
| 96 | return result |
| 97 | |
| 98 | class ConvertingList(list): |
| 99 | """A converting list wrapper.""" |
| 100 | def __getitem__(self, key): |
| 101 | value = list.__getitem__(self, key) |
| 102 | result = self.configurator.convert(value) |
| 103 | #If the converted value is different, save for next time |
| 104 | if value is not result: |
| 105 | self[key] = result |
| 106 | if type(result) in (ConvertingDict, ConvertingList, |
| 107 | ConvertingTuple): |
| 108 | result.parent = self |
| 109 | result.key = key |
| 110 | return result |
| 111 | |
| 112 | def pop(self, idx=-1): |
| 113 | value = list.pop(self, idx) |
| 114 | result = self.configurator.convert(value) |
| 115 | if value is not result: |
| 116 | if type(result) in (ConvertingDict, ConvertingList, |
| 117 | ConvertingTuple): |
| 118 | result.parent = self |
| 119 | return result |
| 120 | |
| 121 | class ConvertingTuple(tuple): |
| 122 | """A converting tuple wrapper.""" |
| 123 | def __getitem__(self, key): |
| 124 | value = tuple.__getitem__(self, key) |
| 125 | result = self.configurator.convert(value) |
| 126 | if value is not result: |
| 127 | if type(result) in (ConvertingDict, ConvertingList, |
| 128 | ConvertingTuple): |
| 129 | result.parent = self |
| 130 | result.key = key |
| 131 | return result |
| 132 | |
| 133 | class BaseConfigurator(object): |
| 134 | """ |
| 135 | The configurator base class which defines some useful defaults. |
| 136 | """ |
| 137 | |
| 138 | CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$') |
| 139 | |
| 140 | WORD_PATTERN = re.compile(r'^\s*(\w+)\s*') |
| 141 | DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*') |
| 142 | INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*') |
| 143 | DIGIT_PATTERN = re.compile(r'^\d+$') |
| 144 | |
| 145 | value_converters = { |
| 146 | 'ext' : 'ext_convert', |
| 147 | 'cfg' : 'cfg_convert', |
| 148 | } |
| 149 | |
| 150 | # We might want to use a different one, e.g. importlib |
| 151 | importer = __import__ |
| 152 | |
| 153 | def __init__(self, config): |
| 154 | self.config = ConvertingDict(config) |
| 155 | self.config.configurator = self |
| 156 | |
| 157 | def resolve(self, s): |
| 158 | """ |
| 159 | Resolve strings to objects using standard import and attribute |
| 160 | syntax. |
| 161 | """ |
| 162 | name = s.split('.') |
| 163 | used = name.pop(0) |
| 164 | found = self.importer(used) |
| 165 | for frag in name: |
| 166 | used += '.' + frag |
| 167 | try: |
| 168 | found = getattr(found, frag) |
| 169 | except AttributeError: |
| 170 | self.importer(used) |
| 171 | found = getattr(found, frag) |
| 172 | return found |
| 173 | |
| 174 | def ext_convert(self, value): |
| 175 | """Default converter for the ext:// protocol.""" |
| 176 | return self.resolve(value) |
| 177 | |
| 178 | def cfg_convert(self, value): |
| 179 | """Default converter for the cfg:// protocol.""" |
| 180 | rest = value |
| 181 | m = self.WORD_PATTERN.match(rest) |
| 182 | if m is None: |
| 183 | raise ValueError("Unable to convert %r" % value) |
| 184 | else: |
| 185 | rest = rest[m.end():] |
| 186 | d = self.config[m.groups()[0]] |
| 187 | #print d, rest |
| 188 | while rest: |
| 189 | m = self.DOT_PATTERN.match(rest) |
| 190 | if m: |
| 191 | d = d[m.groups()[0]] |
| 192 | else: |
| 193 | m = self.INDEX_PATTERN.match(rest) |
| 194 | if m: |
| 195 | idx = m.groups()[0] |
| 196 | if not self.DIGIT_PATTERN.match(idx): |
| 197 | d = d[idx] |
| 198 | else: |
| 199 | try: |
| 200 | n = int(idx) # try as number first (most likely) |
| 201 | d = d[n] |
| 202 | except TypeError: |
| 203 | d = d[idx] |
| 204 | if m: |
| 205 | rest = rest[m.end():] |
| 206 | else: |
| 207 | raise ValueError('Unable to convert ' |
| 208 | '%r at %r' % (value, rest)) |
| 209 | #rest should be empty |
| 210 | return d |
| 211 | |
| 212 | def convert(self, value): |
| 213 | """ |
| 214 | Convert values to an appropriate type. dicts, lists and tuples are |
| 215 | replaced by their converting alternatives. Strings are checked to |
| 216 | see if they have a conversion format and are converted if they do. |
| 217 | """ |
| 218 | if not isinstance(value, ConvertingDict) and isinstance(value, dict): |
| 219 | value = ConvertingDict(value) |
| 220 | value.configurator = self |
| 221 | elif not isinstance(value, ConvertingList) and isinstance(value, list): |
| 222 | value = ConvertingList(value) |
| 223 | value.configurator = self |
| 224 | elif not isinstance(value, ConvertingTuple) and\ |
| 225 | isinstance(value, tuple): |
| 226 | value = ConvertingTuple(value) |
| 227 | value.configurator = self |
| 228 | elif isinstance(value, basestring): # str for py3k |
| 229 | m = self.CONVERT_PATTERN.match(value) |
| 230 | if m: |
| 231 | d = m.groupdict() |
| 232 | prefix = d['prefix'] |
| 233 | converter = self.value_converters.get(prefix, None) |
| 234 | if converter: |
| 235 | suffix = d['suffix'] |
| 236 | converter = getattr(self, converter) |
| 237 | value = converter(suffix) |
| 238 | return value |
| 239 | |
| 240 | def configure_custom(self, config): |
| 241 | """Configure an object with a user-supplied factory.""" |
| 242 | c = config.pop('()') |
| 243 | if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType: |
| 244 | c = self.resolve(c) |
| 245 | props = config.pop('.', None) |
| 246 | # Check for valid identifiers |
| 247 | kwargs = dict([(k, config[k]) for k in config if valid_ident(k)]) |
| 248 | result = c(**kwargs) |
| 249 | if props: |
| 250 | for name, value in props.items(): |
| 251 | setattr(result, name, value) |
| 252 | return result |
| 253 | |
| 254 | def as_tuple(self, value): |
| 255 | """Utility function which converts lists to tuples.""" |
| 256 | if isinstance(value, list): |
| 257 | value = tuple(value) |
| 258 | return value |
| 259 | |
| 260 | class DictConfigurator(BaseConfigurator): |
| 261 | """ |
| 262 | Configure logging using a dictionary-like object to describe the |
| 263 | configuration. |
| 264 | """ |
| 265 | |
| 266 | def configure(self): |
| 267 | """Do the configuration.""" |
| 268 | |
| 269 | config = self.config |
| 270 | if 'version' not in config: |
| 271 | raise ValueError("dictionary doesn't specify a version") |
| 272 | if config['version'] != 1: |
| 273 | raise ValueError("Unsupported version: %s" % config['version']) |
| 274 | incremental = config.pop('incremental', False) |
| 275 | EMPTY_DICT = {} |
| 276 | logging._acquireLock() |
| 277 | try: |
| 278 | if incremental: |
| 279 | handlers = config.get('handlers', EMPTY_DICT) |
| 280 | # incremental handler config only if handler name |
| 281 | # ties in to logging._handlers (Python 2.7) |
| 282 | if sys.version_info[:2] == (2, 7): |
| 283 | for name in handlers: |
| 284 | if name not in logging._handlers: |
| 285 | raise ValueError('No handler found with ' |
| 286 | 'name %r' % name) |
| 287 | else: |
| 288 | try: |
| 289 | handler = logging._handlers[name] |
| 290 | handler_config = handlers[name] |
| 291 | level = handler_config.get('level', None) |
| 292 | if level: |
| 293 | handler.setLevel(_checkLevel(level)) |
| 294 | except StandardError, e: |
| 295 | raise ValueError('Unable to configure handler ' |
| 296 | '%r: %s' % (name, e)) |
| 297 | loggers = config.get('loggers', EMPTY_DICT) |
| 298 | for name in loggers: |
| 299 | try: |
| 300 | self.configure_logger(name, loggers[name], True) |
| 301 | except StandardError, e: |
| 302 | raise ValueError('Unable to configure logger ' |
| 303 | '%r: %s' % (name, e)) |
| 304 | root = config.get('root', None) |
| 305 | if root: |
| 306 | try: |
| 307 | self.configure_root(root, True) |
| 308 | except StandardError, e: |
| 309 | raise ValueError('Unable to configure root ' |
| 310 | 'logger: %s' % e) |
| 311 | else: |
| 312 | disable_existing = config.pop('disable_existing_loggers', True) |
| 313 | |
| 314 | logging._handlers.clear() |
| 315 | del logging._handlerList[:] |
| 316 | |
| 317 | # Do formatters first - they don't refer to anything else |
| 318 | formatters = config.get('formatters', EMPTY_DICT) |
| 319 | for name in formatters: |
| 320 | try: |
| 321 | formatters[name] = self.configure_formatter( |
| 322 | formatters[name]) |
| 323 | except StandardError, e: |
| 324 | raise ValueError('Unable to configure ' |
| 325 | 'formatter %r: %s' % (name, e)) |
| 326 | # Next, do filters - they don't refer to anything else, either |
| 327 | filters = config.get('filters', EMPTY_DICT) |
| 328 | for name in filters: |
| 329 | try: |
| 330 | filters[name] = self.configure_filter(filters[name]) |
| 331 | except StandardError, e: |
| 332 | raise ValueError('Unable to configure ' |
| 333 | 'filter %r: %s' % (name, e)) |
| 334 | |
| 335 | # Next, do handlers - they refer to formatters and filters |
| 336 | # As handlers can refer to other handlers, sort the keys |
| 337 | # to allow a deterministic order of configuration |
| 338 | handlers = config.get('handlers', EMPTY_DICT) |
| 339 | for name in sorted(handlers): |
| 340 | try: |
| 341 | handler = self.configure_handler(handlers[name]) |
| 342 | handler.name = name |
| 343 | handlers[name] = handler |
| 344 | except StandardError, e: |
| 345 | raise ValueError('Unable to configure handler ' |
| 346 | '%r: %s' % (name, e)) |
| 347 | # Next, do loggers - they refer to handlers and filters |
| 348 | |
| 349 | #we don't want to lose the existing loggers, |
| 350 | #since other threads may have pointers to them. |
| 351 | #existing is set to contain all existing loggers, |
| 352 | #and as we go through the new configuration we |
| 353 | #remove any which are configured. At the end, |
| 354 | #what's left in existing is the set of loggers |
| 355 | #which were in the previous configuration but |
| 356 | #which are not in the new configuration. |
| 357 | root = logging.root |
| 358 | existing = root.manager.loggerDict.keys() |
| 359 | #The list needs to be sorted so that we can |
| 360 | #avoid disabling child loggers of explicitly |
| 361 | #named loggers. With a sorted list it is easier |
| 362 | #to find the child loggers. |
| 363 | existing.sort() |
| 364 | #We'll keep the list of existing loggers |
| 365 | #which are children of named loggers here... |
| 366 | child_loggers = [] |
| 367 | #now set up the new ones... |
| 368 | loggers = config.get('loggers', EMPTY_DICT) |
| 369 | for name in loggers: |
| 370 | if name in existing: |
| 371 | i = existing.index(name) |
| 372 | prefixed = name + "." |
| 373 | pflen = len(prefixed) |
| 374 | num_existing = len(existing) |
| 375 | i = i + 1 # look at the entry after name |
| 376 | while (i < num_existing) and\ |
| 377 | (existing[i][:pflen] == prefixed): |
| 378 | child_loggers.append(existing[i]) |
| 379 | i = i + 1 |
| 380 | existing.remove(name) |
| 381 | try: |
| 382 | self.configure_logger(name, loggers[name]) |
| 383 | except StandardError, e: |
| 384 | raise ValueError('Unable to configure logger ' |
| 385 | '%r: %s' % (name, e)) |
| 386 | |
| 387 | #Disable any old loggers. There's no point deleting |
| 388 | #them as other threads may continue to hold references |
| 389 | #and by disabling them, you stop them doing any logging. |
| 390 | #However, don't disable children of named loggers, as that's |
| 391 | #probably not what was intended by the user. |
| 392 | for log in existing: |
| 393 | logger = root.manager.loggerDict[log] |
| 394 | if log in child_loggers: |
| 395 | logger.level = logging.NOTSET |
| 396 | logger.handlers = [] |
| 397 | logger.propagate = True |
| 398 | elif disable_existing: |
| 399 | logger.disabled = True |
| 400 | |
| 401 | # And finally, do the root logger |
| 402 | root = config.get('root', None) |
| 403 | if root: |
| 404 | try: |
| 405 | self.configure_root(root) |
| 406 | except StandardError, e: |
| 407 | raise ValueError('Unable to configure root ' |
| 408 | 'logger: %s' % e) |
| 409 | finally: |
| 410 | logging._releaseLock() |
| 411 | |
| 412 | def configure_formatter(self, config): |
| 413 | """Configure a formatter from a dictionary.""" |
| 414 | if '()' in config: |
| 415 | factory = config['()'] # for use in exception handler |
| 416 | try: |
| 417 | result = self.configure_custom(config) |
| 418 | except TypeError, te: |
| 419 | if "'format'" not in str(te): |
| 420 | raise |
| 421 | #Name of parameter changed from fmt to format. |
| 422 | #Retry with old name. |
| 423 | #This is so that code can be used with older Python versions |
| 424 | #(e.g. by Django) |
| 425 | config['fmt'] = config.pop('format') |
| 426 | config['()'] = factory |
| 427 | result = self.configure_custom(config) |
| 428 | else: |
| 429 | fmt = config.get('format', None) |
| 430 | dfmt = config.get('datefmt', None) |
| 431 | result = logging.Formatter(fmt, dfmt) |
| 432 | return result |
| 433 | |
| 434 | def configure_filter(self, config): |
| 435 | """Configure a filter from a dictionary.""" |
| 436 | if '()' in config: |
| 437 | result = self.configure_custom(config) |
| 438 | else: |
| 439 | name = config.get('name', '') |
| 440 | result = logging.Filter(name) |
| 441 | return result |
| 442 | |
| 443 | def add_filters(self, filterer, filters): |
| 444 | """Add filters to a filterer from a list of names.""" |
| 445 | for f in filters: |
| 446 | try: |
| 447 | filterer.addFilter(self.config['filters'][f]) |
| 448 | except StandardError, e: |
| 449 | raise ValueError('Unable to add filter %r: %s' % (f, e)) |
| 450 | |
| 451 | def configure_handler(self, config): |
| 452 | """Configure a handler from a dictionary.""" |
| 453 | formatter = config.pop('formatter', None) |
| 454 | if formatter: |
| 455 | try: |
| 456 | formatter = self.config['formatters'][formatter] |
| 457 | except StandardError, e: |
| 458 | raise ValueError('Unable to set formatter ' |
| 459 | '%r: %s' % (formatter, e)) |
| 460 | level = config.pop('level', None) |
| 461 | filters = config.pop('filters', None) |
| 462 | if '()' in config: |
| 463 | c = config.pop('()') |
| 464 | if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType: |
| 465 | c = self.resolve(c) |
| 466 | factory = c |
| 467 | else: |
| 468 | klass = self.resolve(config.pop('class')) |
| 469 | #Special case for handler which refers to another handler |
| 470 | if issubclass(klass, logging.handlers.MemoryHandler) and\ |
| 471 | 'target' in config: |
| 472 | try: |
| 473 | config['target'] = self.config['handlers'][config['target']] |
| 474 | except StandardError, e: |
| 475 | raise ValueError('Unable to set target handler ' |
| 476 | '%r: %s' % (config['target'], e)) |
| 477 | elif issubclass(klass, logging.handlers.SMTPHandler) and\ |
| 478 | 'mailhost' in config: |
| 479 | config['mailhost'] = self.as_tuple(config['mailhost']) |
| 480 | elif issubclass(klass, logging.handlers.SysLogHandler) and\ |
| 481 | 'address' in config: |
| 482 | config['address'] = self.as_tuple(config['address']) |
| 483 | factory = klass |
| 484 | kwargs = dict([(k, config[k]) for k in config if valid_ident(k)]) |
| 485 | try: |
| 486 | result = factory(**kwargs) |
| 487 | except TypeError, te: |
| 488 | if "'stream'" not in str(te): |
| 489 | raise |
| 490 | #The argument name changed from strm to stream |
| 491 | #Retry with old name. |
| 492 | #This is so that code can be used with older Python versions |
| 493 | #(e.g. by Django) |
| 494 | kwargs['strm'] = kwargs.pop('stream') |
| 495 | result = factory(**kwargs) |
| 496 | if formatter: |
| 497 | result.setFormatter(formatter) |
| 498 | if level is not None: |
| 499 | result.setLevel(_checkLevel(level)) |
| 500 | if filters: |
| 501 | self.add_filters(result, filters) |
| 502 | return result |
| 503 | |
| 504 | def add_handlers(self, logger, handlers): |
| 505 | """Add handlers to a logger from a list of names.""" |
| 506 | for h in handlers: |
| 507 | try: |
| 508 | logger.addHandler(self.config['handlers'][h]) |
| 509 | except StandardError, e: |
| 510 | raise ValueError('Unable to add handler %r: %s' % (h, e)) |
| 511 | |
| 512 | def common_logger_config(self, logger, config, incremental=False): |
| 513 | """ |
| 514 | Perform configuration which is common to root and non-root loggers. |
| 515 | """ |
| 516 | level = config.get('level', None) |
| 517 | if level is not None: |
| 518 | logger.setLevel(_checkLevel(level)) |
| 519 | if not incremental: |
| 520 | #Remove any existing handlers |
| 521 | for h in logger.handlers[:]: |
| 522 | logger.removeHandler(h) |
| 523 | handlers = config.get('handlers', None) |
| 524 | if handlers: |
| 525 | self.add_handlers(logger, handlers) |
| 526 | filters = config.get('filters', None) |
| 527 | if filters: |
| 528 | self.add_filters(logger, filters) |
| 529 | |
| 530 | def configure_logger(self, name, config, incremental=False): |
| 531 | """Configure a non-root logger from a dictionary.""" |
| 532 | logger = logging.getLogger(name) |
| 533 | self.common_logger_config(logger, config, incremental) |
| 534 | propagate = config.get('propagate', None) |
| 535 | if propagate is not None: |
| 536 | logger.propagate = propagate |
| 537 | |
| 538 | def configure_root(self, config, incremental=False): |
| 539 | """Configure a root logger from a dictionary.""" |
| 540 | root = logging.getLogger() |
| 541 | self.common_logger_config(root, config, incremental) |
| 542 | |
| 543 | dictConfigClass = DictConfigurator |
| 544 | |
| 545 | def dictConfig(config): |
| 546 | """Configure logging using a dictionary.""" |
| 547 | dictConfigClass(config).configure() |