config.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. # Copyright 2001-2023 by Vinay Sajip. All Rights Reserved.
  2. #
  3. # Permission to use, copy, modify, and distribute this software and its
  4. # documentation for any purpose and without fee is hereby granted,
  5. # provided that the above copyright notice appear in all copies and that
  6. # both that copyright notice and this permission notice appear in
  7. # supporting documentation, and that the name of Vinay Sajip
  8. # not be used in advertising or publicity pertaining to distribution
  9. # of the software without specific, written prior permission.
  10. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
  11. # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  12. # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
  13. # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  14. # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """
  17. Configuration functions for the logging package for Python. The core package
  18. is based on PEP 282 and comments thereto in comp.lang.python, and influenced
  19. by Apache's log4j system.
  20. Copyright (C) 2001-2022 Vinay Sajip. All Rights Reserved.
  21. To use, simply 'import logging' and log away!
  22. """
  23. import errno
  24. import functools
  25. import io
  26. import logging
  27. import logging.handlers
  28. import os
  29. import queue
  30. import re
  31. import struct
  32. import threading
  33. import traceback
  34. from socketserver import ThreadingTCPServer, StreamRequestHandler
  35. DEFAULT_LOGGING_CONFIG_PORT = 9030
  36. RESET_ERROR = errno.ECONNRESET
  37. #
  38. # The following code implements a socket listener for on-the-fly
  39. # reconfiguration of logging.
  40. #
  41. # _listener holds the server object doing the listening
  42. _listener = None
  43. def fileConfig(fname, defaults=None, disable_existing_loggers=True, encoding=None):
  44. """
  45. Read the logging configuration from a ConfigParser-format file.
  46. This can be called several times from an application, allowing an end user
  47. the ability to select from various pre-canned configurations (if the
  48. developer provides a mechanism to present the choices and load the chosen
  49. configuration).
  50. """
  51. import configparser
  52. if isinstance(fname, str):
  53. if not os.path.exists(fname):
  54. raise FileNotFoundError(f"{fname} doesn't exist")
  55. elif not os.path.getsize(fname):
  56. raise RuntimeError(f'{fname} is an empty file')
  57. if isinstance(fname, configparser.RawConfigParser):
  58. cp = fname
  59. else:
  60. try:
  61. cp = configparser.ConfigParser(defaults)
  62. if hasattr(fname, 'readline'):
  63. cp.read_file(fname)
  64. else:
  65. encoding = io.text_encoding(encoding)
  66. cp.read(fname, encoding=encoding)
  67. except configparser.ParsingError as e:
  68. raise RuntimeError(f'{fname} is invalid: {e}')
  69. formatters = _create_formatters(cp)
  70. # critical section
  71. logging._acquireLock()
  72. try:
  73. _clearExistingHandlers()
  74. # Handlers add themselves to logging._handlers
  75. handlers = _install_handlers(cp, formatters)
  76. _install_loggers(cp, handlers, disable_existing_loggers)
  77. finally:
  78. logging._releaseLock()
  79. def _resolve(name):
  80. """Resolve a dotted name to a global object."""
  81. name = name.split('.')
  82. used = name.pop(0)
  83. found = __import__(used)
  84. for n in name:
  85. used = used + '.' + n
  86. try:
  87. found = getattr(found, n)
  88. except AttributeError:
  89. __import__(used)
  90. found = getattr(found, n)
  91. return found
  92. def _strip_spaces(alist):
  93. return map(str.strip, alist)
  94. def _create_formatters(cp):
  95. """Create and return formatters"""
  96. flist = cp["formatters"]["keys"]
  97. if not len(flist):
  98. return {}
  99. flist = flist.split(",")
  100. flist = _strip_spaces(flist)
  101. formatters = {}
  102. for form in flist:
  103. sectname = "formatter_%s" % form
  104. fs = cp.get(sectname, "format", raw=True, fallback=None)
  105. dfs = cp.get(sectname, "datefmt", raw=True, fallback=None)
  106. stl = cp.get(sectname, "style", raw=True, fallback='%')
  107. defaults = cp.get(sectname, "defaults", raw=True, fallback=None)
  108. c = logging.Formatter
  109. class_name = cp[sectname].get("class")
  110. if class_name:
  111. c = _resolve(class_name)
  112. if defaults is not None:
  113. defaults = eval(defaults, vars(logging))
  114. f = c(fs, dfs, stl, defaults=defaults)
  115. else:
  116. f = c(fs, dfs, stl)
  117. formatters[form] = f
  118. return formatters
  119. def _install_handlers(cp, formatters):
  120. """Install and return handlers"""
  121. hlist = cp["handlers"]["keys"]
  122. if not len(hlist):
  123. return {}
  124. hlist = hlist.split(",")
  125. hlist = _strip_spaces(hlist)
  126. handlers = {}
  127. fixups = [] #for inter-handler references
  128. for hand in hlist:
  129. section = cp["handler_%s" % hand]
  130. klass = section["class"]
  131. fmt = section.get("formatter", "")
  132. try:
  133. klass = eval(klass, vars(logging))
  134. except (AttributeError, NameError):
  135. klass = _resolve(klass)
  136. args = section.get("args", '()')
  137. args = eval(args, vars(logging))
  138. kwargs = section.get("kwargs", '{}')
  139. kwargs = eval(kwargs, vars(logging))
  140. h = klass(*args, **kwargs)
  141. h.name = hand
  142. if "level" in section:
  143. level = section["level"]
  144. h.setLevel(level)
  145. if len(fmt):
  146. h.setFormatter(formatters[fmt])
  147. if issubclass(klass, logging.handlers.MemoryHandler):
  148. target = section.get("target", "")
  149. if len(target): #the target handler may not be loaded yet, so keep for later...
  150. fixups.append((h, target))
  151. handlers[hand] = h
  152. #now all handlers are loaded, fixup inter-handler references...
  153. for h, t in fixups:
  154. h.setTarget(handlers[t])
  155. return handlers
  156. def _handle_existing_loggers(existing, child_loggers, disable_existing):
  157. """
  158. When (re)configuring logging, handle loggers which were in the previous
  159. configuration but are not in the new configuration. There's no point
  160. deleting them as other threads may continue to hold references to them;
  161. and by disabling them, you stop them doing any logging.
  162. However, don't disable children of named loggers, as that's probably not
  163. what was intended by the user. Also, allow existing loggers to NOT be
  164. disabled if disable_existing is false.
  165. """
  166. root = logging.root
  167. for log in existing:
  168. logger = root.manager.loggerDict[log]
  169. if log in child_loggers:
  170. if not isinstance(logger, logging.PlaceHolder):
  171. logger.setLevel(logging.NOTSET)
  172. logger.handlers = []
  173. logger.propagate = True
  174. else:
  175. logger.disabled = disable_existing
  176. def _install_loggers(cp, handlers, disable_existing):
  177. """Create and install loggers"""
  178. # configure the root first
  179. llist = cp["loggers"]["keys"]
  180. llist = llist.split(",")
  181. llist = list(_strip_spaces(llist))
  182. llist.remove("root")
  183. section = cp["logger_root"]
  184. root = logging.root
  185. log = root
  186. if "level" in section:
  187. level = section["level"]
  188. log.setLevel(level)
  189. for h in root.handlers[:]:
  190. root.removeHandler(h)
  191. hlist = section["handlers"]
  192. if len(hlist):
  193. hlist = hlist.split(",")
  194. hlist = _strip_spaces(hlist)
  195. for hand in hlist:
  196. log.addHandler(handlers[hand])
  197. #and now the others...
  198. #we don't want to lose the existing loggers,
  199. #since other threads may have pointers to them.
  200. #existing is set to contain all existing loggers,
  201. #and as we go through the new configuration we
  202. #remove any which are configured. At the end,
  203. #what's left in existing is the set of loggers
  204. #which were in the previous configuration but
  205. #which are not in the new configuration.
  206. existing = list(root.manager.loggerDict.keys())
  207. #The list needs to be sorted so that we can
  208. #avoid disabling child loggers of explicitly
  209. #named loggers. With a sorted list it is easier
  210. #to find the child loggers.
  211. existing.sort()
  212. #We'll keep the list of existing loggers
  213. #which are children of named loggers here...
  214. child_loggers = []
  215. #now set up the new ones...
  216. for log in llist:
  217. section = cp["logger_%s" % log]
  218. qn = section["qualname"]
  219. propagate = section.getint("propagate", fallback=1)
  220. logger = logging.getLogger(qn)
  221. if qn in existing:
  222. i = existing.index(qn) + 1 # start with the entry after qn
  223. prefixed = qn + "."
  224. pflen = len(prefixed)
  225. num_existing = len(existing)
  226. while i < num_existing:
  227. if existing[i][:pflen] == prefixed:
  228. child_loggers.append(existing[i])
  229. i += 1
  230. existing.remove(qn)
  231. if "level" in section:
  232. level = section["level"]
  233. logger.setLevel(level)
  234. for h in logger.handlers[:]:
  235. logger.removeHandler(h)
  236. logger.propagate = propagate
  237. logger.disabled = 0
  238. hlist = section["handlers"]
  239. if len(hlist):
  240. hlist = hlist.split(",")
  241. hlist = _strip_spaces(hlist)
  242. for hand in hlist:
  243. logger.addHandler(handlers[hand])
  244. #Disable any old loggers. There's no point deleting
  245. #them as other threads may continue to hold references
  246. #and by disabling them, you stop them doing any logging.
  247. #However, don't disable children of named loggers, as that's
  248. #probably not what was intended by the user.
  249. #for log in existing:
  250. # logger = root.manager.loggerDict[log]
  251. # if log in child_loggers:
  252. # logger.level = logging.NOTSET
  253. # logger.handlers = []
  254. # logger.propagate = 1
  255. # elif disable_existing_loggers:
  256. # logger.disabled = 1
  257. _handle_existing_loggers(existing, child_loggers, disable_existing)
  258. def _clearExistingHandlers():
  259. """Clear and close existing handlers"""
  260. logging._handlers.clear()
  261. logging.shutdown(logging._handlerList[:])
  262. del logging._handlerList[:]
  263. IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
  264. def valid_ident(s):
  265. m = IDENTIFIER.match(s)
  266. if not m:
  267. raise ValueError('Not a valid Python identifier: %r' % s)
  268. return True
  269. class ConvertingMixin(object):
  270. """For ConvertingXXX's, this mixin class provides common functions"""
  271. def convert_with_key(self, key, value, replace=True):
  272. result = self.configurator.convert(value)
  273. #If the converted value is different, save for next time
  274. if value is not result:
  275. if replace:
  276. self[key] = result
  277. if type(result) in (ConvertingDict, ConvertingList,
  278. ConvertingTuple):
  279. result.parent = self
  280. result.key = key
  281. return result
  282. def convert(self, value):
  283. result = self.configurator.convert(value)
  284. if value is not result:
  285. if type(result) in (ConvertingDict, ConvertingList,
  286. ConvertingTuple):
  287. result.parent = self
  288. return result
  289. # The ConvertingXXX classes are wrappers around standard Python containers,
  290. # and they serve to convert any suitable values in the container. The
  291. # conversion converts base dicts, lists and tuples to their wrapped
  292. # equivalents, whereas strings which match a conversion format are converted
  293. # appropriately.
  294. #
  295. # Each wrapper should have a configurator attribute holding the actual
  296. # configurator to use for conversion.
  297. class ConvertingDict(dict, ConvertingMixin):
  298. """A converting dictionary wrapper."""
  299. def __getitem__(self, key):
  300. value = dict.__getitem__(self, key)
  301. return self.convert_with_key(key, value)
  302. def get(self, key, default=None):
  303. value = dict.get(self, key, default)
  304. return self.convert_with_key(key, value)
  305. def pop(self, key, default=None):
  306. value = dict.pop(self, key, default)
  307. return self.convert_with_key(key, value, replace=False)
  308. class ConvertingList(list, ConvertingMixin):
  309. """A converting list wrapper."""
  310. def __getitem__(self, key):
  311. value = list.__getitem__(self, key)
  312. return self.convert_with_key(key, value)
  313. def pop(self, idx=-1):
  314. value = list.pop(self, idx)
  315. return self.convert(value)
  316. class ConvertingTuple(tuple, ConvertingMixin):
  317. """A converting tuple wrapper."""
  318. def __getitem__(self, key):
  319. value = tuple.__getitem__(self, key)
  320. # Can't replace a tuple entry.
  321. return self.convert_with_key(key, value, replace=False)
  322. class BaseConfigurator(object):
  323. """
  324. The configurator base class which defines some useful defaults.
  325. """
  326. CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')
  327. WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
  328. DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*')
  329. INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*')
  330. DIGIT_PATTERN = re.compile(r'^\d+$')
  331. value_converters = {
  332. 'ext' : 'ext_convert',
  333. 'cfg' : 'cfg_convert',
  334. }
  335. # We might want to use a different one, e.g. importlib
  336. importer = staticmethod(__import__)
  337. def __init__(self, config):
  338. self.config = ConvertingDict(config)
  339. self.config.configurator = self
  340. def resolve(self, s):
  341. """
  342. Resolve strings to objects using standard import and attribute
  343. syntax.
  344. """
  345. name = s.split('.')
  346. used = name.pop(0)
  347. try:
  348. found = self.importer(used)
  349. for frag in name:
  350. used += '.' + frag
  351. try:
  352. found = getattr(found, frag)
  353. except AttributeError:
  354. self.importer(used)
  355. found = getattr(found, frag)
  356. return found
  357. except ImportError as e:
  358. v = ValueError('Cannot resolve %r: %s' % (s, e))
  359. raise v from e
  360. def ext_convert(self, value):
  361. """Default converter for the ext:// protocol."""
  362. return self.resolve(value)
  363. def cfg_convert(self, value):
  364. """Default converter for the cfg:// protocol."""
  365. rest = value
  366. m = self.WORD_PATTERN.match(rest)
  367. if m is None:
  368. raise ValueError("Unable to convert %r" % value)
  369. else:
  370. rest = rest[m.end():]
  371. d = self.config[m.groups()[0]]
  372. #print d, rest
  373. while rest:
  374. m = self.DOT_PATTERN.match(rest)
  375. if m:
  376. d = d[m.groups()[0]]
  377. else:
  378. m = self.INDEX_PATTERN.match(rest)
  379. if m:
  380. idx = m.groups()[0]
  381. if not self.DIGIT_PATTERN.match(idx):
  382. d = d[idx]
  383. else:
  384. try:
  385. n = int(idx) # try as number first (most likely)
  386. d = d[n]
  387. except TypeError:
  388. d = d[idx]
  389. if m:
  390. rest = rest[m.end():]
  391. else:
  392. raise ValueError('Unable to convert '
  393. '%r at %r' % (value, rest))
  394. #rest should be empty
  395. return d
  396. def convert(self, value):
  397. """
  398. Convert values to an appropriate type. dicts, lists and tuples are
  399. replaced by their converting alternatives. Strings are checked to
  400. see if they have a conversion format and are converted if they do.
  401. """
  402. if not isinstance(value, ConvertingDict) and isinstance(value, dict):
  403. value = ConvertingDict(value)
  404. value.configurator = self
  405. elif not isinstance(value, ConvertingList) and isinstance(value, list):
  406. value = ConvertingList(value)
  407. value.configurator = self
  408. elif not isinstance(value, ConvertingTuple) and\
  409. isinstance(value, tuple) and not hasattr(value, '_fields'):
  410. value = ConvertingTuple(value)
  411. value.configurator = self
  412. elif isinstance(value, str): # str for py3k
  413. m = self.CONVERT_PATTERN.match(value)
  414. if m:
  415. d = m.groupdict()
  416. prefix = d['prefix']
  417. converter = self.value_converters.get(prefix, None)
  418. if converter:
  419. suffix = d['suffix']
  420. converter = getattr(self, converter)
  421. value = converter(suffix)
  422. return value
  423. def configure_custom(self, config):
  424. """Configure an object with a user-supplied factory."""
  425. c = config.pop('()')
  426. if not callable(c):
  427. c = self.resolve(c)
  428. # Check for valid identifiers
  429. kwargs = {k: config[k] for k in config if (k != '.' and valid_ident(k))}
  430. result = c(**kwargs)
  431. props = config.pop('.', None)
  432. if props:
  433. for name, value in props.items():
  434. setattr(result, name, value)
  435. return result
  436. def as_tuple(self, value):
  437. """Utility function which converts lists to tuples."""
  438. if isinstance(value, list):
  439. value = tuple(value)
  440. return value
  441. class DictConfigurator(BaseConfigurator):
  442. """
  443. Configure logging using a dictionary-like object to describe the
  444. configuration.
  445. """
  446. def configure(self):
  447. """Do the configuration."""
  448. config = self.config
  449. if 'version' not in config:
  450. raise ValueError("dictionary doesn't specify a version")
  451. if config['version'] != 1:
  452. raise ValueError("Unsupported version: %s" % config['version'])
  453. incremental = config.pop('incremental', False)
  454. EMPTY_DICT = {}
  455. logging._acquireLock()
  456. try:
  457. if incremental:
  458. handlers = config.get('handlers', EMPTY_DICT)
  459. for name in handlers:
  460. if name not in logging._handlers:
  461. raise ValueError('No handler found with '
  462. 'name %r' % name)
  463. else:
  464. try:
  465. handler = logging._handlers[name]
  466. handler_config = handlers[name]
  467. level = handler_config.get('level', None)
  468. if level:
  469. handler.setLevel(logging._checkLevel(level))
  470. except Exception as e:
  471. raise ValueError('Unable to configure handler '
  472. '%r' % name) from e
  473. loggers = config.get('loggers', EMPTY_DICT)
  474. for name in loggers:
  475. try:
  476. self.configure_logger(name, loggers[name], True)
  477. except Exception as e:
  478. raise ValueError('Unable to configure logger '
  479. '%r' % name) from e
  480. root = config.get('root', None)
  481. if root:
  482. try:
  483. self.configure_root(root, True)
  484. except Exception as e:
  485. raise ValueError('Unable to configure root '
  486. 'logger') from e
  487. else:
  488. disable_existing = config.pop('disable_existing_loggers', True)
  489. _clearExistingHandlers()
  490. # Do formatters first - they don't refer to anything else
  491. formatters = config.get('formatters', EMPTY_DICT)
  492. for name in formatters:
  493. try:
  494. formatters[name] = self.configure_formatter(
  495. formatters[name])
  496. except Exception as e:
  497. raise ValueError('Unable to configure '
  498. 'formatter %r' % name) from e
  499. # Next, do filters - they don't refer to anything else, either
  500. filters = config.get('filters', EMPTY_DICT)
  501. for name in filters:
  502. try:
  503. filters[name] = self.configure_filter(filters[name])
  504. except Exception as e:
  505. raise ValueError('Unable to configure '
  506. 'filter %r' % name) from e
  507. # Next, do handlers - they refer to formatters and filters
  508. # As handlers can refer to other handlers, sort the keys
  509. # to allow a deterministic order of configuration
  510. handlers = config.get('handlers', EMPTY_DICT)
  511. deferred = []
  512. for name in sorted(handlers):
  513. try:
  514. handler = self.configure_handler(handlers[name])
  515. handler.name = name
  516. handlers[name] = handler
  517. except Exception as e:
  518. if ' not configured yet' in str(e.__cause__):
  519. deferred.append(name)
  520. else:
  521. raise ValueError('Unable to configure handler '
  522. '%r' % name) from e
  523. # Now do any that were deferred
  524. for name in deferred:
  525. try:
  526. handler = self.configure_handler(handlers[name])
  527. handler.name = name
  528. handlers[name] = handler
  529. except Exception as e:
  530. raise ValueError('Unable to configure handler '
  531. '%r' % name) from e
  532. # Next, do loggers - they refer to handlers and filters
  533. #we don't want to lose the existing loggers,
  534. #since other threads may have pointers to them.
  535. #existing is set to contain all existing loggers,
  536. #and as we go through the new configuration we
  537. #remove any which are configured. At the end,
  538. #what's left in existing is the set of loggers
  539. #which were in the previous configuration but
  540. #which are not in the new configuration.
  541. root = logging.root
  542. existing = list(root.manager.loggerDict.keys())
  543. #The list needs to be sorted so that we can
  544. #avoid disabling child loggers of explicitly
  545. #named loggers. With a sorted list it is easier
  546. #to find the child loggers.
  547. existing.sort()
  548. #We'll keep the list of existing loggers
  549. #which are children of named loggers here...
  550. child_loggers = []
  551. #now set up the new ones...
  552. loggers = config.get('loggers', EMPTY_DICT)
  553. for name in loggers:
  554. if name in existing:
  555. i = existing.index(name) + 1 # look after name
  556. prefixed = name + "."
  557. pflen = len(prefixed)
  558. num_existing = len(existing)
  559. while i < num_existing:
  560. if existing[i][:pflen] == prefixed:
  561. child_loggers.append(existing[i])
  562. i += 1
  563. existing.remove(name)
  564. try:
  565. self.configure_logger(name, loggers[name])
  566. except Exception as e:
  567. raise ValueError('Unable to configure logger '
  568. '%r' % name) from e
  569. #Disable any old loggers. There's no point deleting
  570. #them as other threads may continue to hold references
  571. #and by disabling them, you stop them doing any logging.
  572. #However, don't disable children of named loggers, as that's
  573. #probably not what was intended by the user.
  574. #for log in existing:
  575. # logger = root.manager.loggerDict[log]
  576. # if log in child_loggers:
  577. # logger.level = logging.NOTSET
  578. # logger.handlers = []
  579. # logger.propagate = True
  580. # elif disable_existing:
  581. # logger.disabled = True
  582. _handle_existing_loggers(existing, child_loggers,
  583. disable_existing)
  584. # And finally, do the root logger
  585. root = config.get('root', None)
  586. if root:
  587. try:
  588. self.configure_root(root)
  589. except Exception as e:
  590. raise ValueError('Unable to configure root '
  591. 'logger') from e
  592. finally:
  593. logging._releaseLock()
  594. def configure_formatter(self, config):
  595. """Configure a formatter from a dictionary."""
  596. if '()' in config:
  597. factory = config['()'] # for use in exception handler
  598. try:
  599. result = self.configure_custom(config)
  600. except TypeError as te:
  601. if "'format'" not in str(te):
  602. raise
  603. #Name of parameter changed from fmt to format.
  604. #Retry with old name.
  605. #This is so that code can be used with older Python versions
  606. #(e.g. by Django)
  607. config['fmt'] = config.pop('format')
  608. config['()'] = factory
  609. result = self.configure_custom(config)
  610. else:
  611. fmt = config.get('format', None)
  612. dfmt = config.get('datefmt', None)
  613. style = config.get('style', '%')
  614. cname = config.get('class', None)
  615. defaults = config.get('defaults', None)
  616. if not cname:
  617. c = logging.Formatter
  618. else:
  619. c = _resolve(cname)
  620. kwargs = {}
  621. # Add defaults only if it exists.
  622. # Prevents TypeError in custom formatter callables that do not
  623. # accept it.
  624. if defaults is not None:
  625. kwargs['defaults'] = defaults
  626. # A TypeError would be raised if "validate" key is passed in with a formatter callable
  627. # that does not accept "validate" as a parameter
  628. if 'validate' in config: # if user hasn't mentioned it, the default will be fine
  629. result = c(fmt, dfmt, style, config['validate'], **kwargs)
  630. else:
  631. result = c(fmt, dfmt, style, **kwargs)
  632. return result
  633. def configure_filter(self, config):
  634. """Configure a filter from a dictionary."""
  635. if '()' in config:
  636. result = self.configure_custom(config)
  637. else:
  638. name = config.get('name', '')
  639. result = logging.Filter(name)
  640. return result
  641. def add_filters(self, filterer, filters):
  642. """Add filters to a filterer from a list of names."""
  643. for f in filters:
  644. try:
  645. if callable(f) or callable(getattr(f, 'filter', None)):
  646. filter_ = f
  647. else:
  648. filter_ = self.config['filters'][f]
  649. filterer.addFilter(filter_)
  650. except Exception as e:
  651. raise ValueError('Unable to add filter %r' % f) from e
  652. def _configure_queue_handler(self, klass, **kwargs):
  653. if 'queue' in kwargs:
  654. q = kwargs['queue']
  655. else:
  656. q = queue.Queue() # unbounded
  657. rhl = kwargs.get('respect_handler_level', False)
  658. if 'listener' in kwargs:
  659. lklass = kwargs['listener']
  660. else:
  661. lklass = logging.handlers.QueueListener
  662. listener = lklass(q, *kwargs.get('handlers', []), respect_handler_level=rhl)
  663. handler = klass(q)
  664. handler.listener = listener
  665. return handler
  666. def configure_handler(self, config):
  667. """Configure a handler from a dictionary."""
  668. config_copy = dict(config) # for restoring in case of error
  669. formatter = config.pop('formatter', None)
  670. if formatter:
  671. try:
  672. formatter = self.config['formatters'][formatter]
  673. except Exception as e:
  674. raise ValueError('Unable to set formatter '
  675. '%r' % formatter) from e
  676. level = config.pop('level', None)
  677. filters = config.pop('filters', None)
  678. if '()' in config:
  679. c = config.pop('()')
  680. if not callable(c):
  681. c = self.resolve(c)
  682. factory = c
  683. else:
  684. cname = config.pop('class')
  685. if callable(cname):
  686. klass = cname
  687. else:
  688. klass = self.resolve(cname)
  689. if issubclass(klass, logging.handlers.MemoryHandler) and\
  690. 'target' in config:
  691. # Special case for handler which refers to another handler
  692. try:
  693. tn = config['target']
  694. th = self.config['handlers'][tn]
  695. if not isinstance(th, logging.Handler):
  696. config.update(config_copy) # restore for deferred cfg
  697. raise TypeError('target not configured yet')
  698. config['target'] = th
  699. except Exception as e:
  700. raise ValueError('Unable to set target handler %r' % tn) from e
  701. elif issubclass(klass, logging.handlers.QueueHandler):
  702. # Another special case for handler which refers to other handlers
  703. # if 'handlers' not in config:
  704. # raise ValueError('No handlers specified for a QueueHandler')
  705. if 'queue' in config:
  706. from multiprocessing.queues import Queue as MPQueue
  707. qspec = config['queue']
  708. if not isinstance(qspec, (queue.Queue, MPQueue)):
  709. if isinstance(qspec, str):
  710. q = self.resolve(qspec)
  711. if not callable(q):
  712. raise TypeError('Invalid queue specifier %r' % qspec)
  713. q = q()
  714. elif isinstance(qspec, dict):
  715. if '()' not in qspec:
  716. raise TypeError('Invalid queue specifier %r' % qspec)
  717. q = self.configure_custom(dict(qspec))
  718. else:
  719. raise TypeError('Invalid queue specifier %r' % qspec)
  720. config['queue'] = q
  721. if 'listener' in config:
  722. lspec = config['listener']
  723. if isinstance(lspec, type):
  724. if not issubclass(lspec, logging.handlers.QueueListener):
  725. raise TypeError('Invalid listener specifier %r' % lspec)
  726. else:
  727. if isinstance(lspec, str):
  728. listener = self.resolve(lspec)
  729. if isinstance(listener, type) and\
  730. not issubclass(listener, logging.handlers.QueueListener):
  731. raise TypeError('Invalid listener specifier %r' % lspec)
  732. elif isinstance(lspec, dict):
  733. if '()' not in lspec:
  734. raise TypeError('Invalid listener specifier %r' % lspec)
  735. listener = self.configure_custom(dict(lspec))
  736. else:
  737. raise TypeError('Invalid listener specifier %r' % lspec)
  738. if not callable(listener):
  739. raise TypeError('Invalid listener specifier %r' % lspec)
  740. config['listener'] = listener
  741. if 'handlers' in config:
  742. hlist = []
  743. try:
  744. for hn in config['handlers']:
  745. h = self.config['handlers'][hn]
  746. if not isinstance(h, logging.Handler):
  747. config.update(config_copy) # restore for deferred cfg
  748. raise TypeError('Required handler %r '
  749. 'is not configured yet' % hn)
  750. hlist.append(h)
  751. except Exception as e:
  752. raise ValueError('Unable to set required handler %r' % hn) from e
  753. config['handlers'] = hlist
  754. elif issubclass(klass, logging.handlers.SMTPHandler) and\
  755. 'mailhost' in config:
  756. config['mailhost'] = self.as_tuple(config['mailhost'])
  757. elif issubclass(klass, logging.handlers.SysLogHandler) and\
  758. 'address' in config:
  759. config['address'] = self.as_tuple(config['address'])
  760. if issubclass(klass, logging.handlers.QueueHandler):
  761. factory = functools.partial(self._configure_queue_handler, klass)
  762. else:
  763. factory = klass
  764. kwargs = {k: config[k] for k in config if (k != '.' and valid_ident(k))}
  765. try:
  766. result = factory(**kwargs)
  767. except TypeError as te:
  768. if "'stream'" not in str(te):
  769. raise
  770. #The argument name changed from strm to stream
  771. #Retry with old name.
  772. #This is so that code can be used with older Python versions
  773. #(e.g. by Django)
  774. kwargs['strm'] = kwargs.pop('stream')
  775. result = factory(**kwargs)
  776. if formatter:
  777. result.setFormatter(formatter)
  778. if level is not None:
  779. result.setLevel(logging._checkLevel(level))
  780. if filters:
  781. self.add_filters(result, filters)
  782. props = config.pop('.', None)
  783. if props:
  784. for name, value in props.items():
  785. setattr(result, name, value)
  786. return result
  787. def add_handlers(self, logger, handlers):
  788. """Add handlers to a logger from a list of names."""
  789. for h in handlers:
  790. try:
  791. logger.addHandler(self.config['handlers'][h])
  792. except Exception as e:
  793. raise ValueError('Unable to add handler %r' % h) from e
  794. def common_logger_config(self, logger, config, incremental=False):
  795. """
  796. Perform configuration which is common to root and non-root loggers.
  797. """
  798. level = config.get('level', None)
  799. if level is not None:
  800. logger.setLevel(logging._checkLevel(level))
  801. if not incremental:
  802. #Remove any existing handlers
  803. for h in logger.handlers[:]:
  804. logger.removeHandler(h)
  805. handlers = config.get('handlers', None)
  806. if handlers:
  807. self.add_handlers(logger, handlers)
  808. filters = config.get('filters', None)
  809. if filters:
  810. self.add_filters(logger, filters)
  811. def configure_logger(self, name, config, incremental=False):
  812. """Configure a non-root logger from a dictionary."""
  813. logger = logging.getLogger(name)
  814. self.common_logger_config(logger, config, incremental)
  815. logger.disabled = False
  816. propagate = config.get('propagate', None)
  817. if propagate is not None:
  818. logger.propagate = propagate
  819. def configure_root(self, config, incremental=False):
  820. """Configure a root logger from a dictionary."""
  821. root = logging.getLogger()
  822. self.common_logger_config(root, config, incremental)
  823. dictConfigClass = DictConfigurator
  824. def dictConfig(config):
  825. """Configure logging using a dictionary."""
  826. dictConfigClass(config).configure()
  827. def listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None):
  828. """
  829. Start up a socket server on the specified port, and listen for new
  830. configurations.
  831. These will be sent as a file suitable for processing by fileConfig().
  832. Returns a Thread object on which you can call start() to start the server,
  833. and which you can join() when appropriate. To stop the server, call
  834. stopListening().
  835. Use the ``verify`` argument to verify any bytes received across the wire
  836. from a client. If specified, it should be a callable which receives a
  837. single argument - the bytes of configuration data received across the
  838. network - and it should return either ``None``, to indicate that the
  839. passed in bytes could not be verified and should be discarded, or a
  840. byte string which is then passed to the configuration machinery as
  841. normal. Note that you can return transformed bytes, e.g. by decrypting
  842. the bytes passed in.
  843. """
  844. class ConfigStreamHandler(StreamRequestHandler):
  845. """
  846. Handler for a logging configuration request.
  847. It expects a completely new logging configuration and uses fileConfig
  848. to install it.
  849. """
  850. def handle(self):
  851. """
  852. Handle a request.
  853. Each request is expected to be a 4-byte length, packed using
  854. struct.pack(">L", n), followed by the config file.
  855. Uses fileConfig() to do the grunt work.
  856. """
  857. try:
  858. conn = self.connection
  859. chunk = conn.recv(4)
  860. if len(chunk) == 4:
  861. slen = struct.unpack(">L", chunk)[0]
  862. chunk = self.connection.recv(slen)
  863. while len(chunk) < slen:
  864. chunk = chunk + conn.recv(slen - len(chunk))
  865. if self.server.verify is not None:
  866. chunk = self.server.verify(chunk)
  867. if chunk is not None: # verified, can process
  868. chunk = chunk.decode("utf-8")
  869. try:
  870. import json
  871. d =json.loads(chunk)
  872. assert isinstance(d, dict)
  873. dictConfig(d)
  874. except Exception:
  875. #Apply new configuration.
  876. file = io.StringIO(chunk)
  877. try:
  878. fileConfig(file)
  879. except Exception:
  880. traceback.print_exc()
  881. if self.server.ready:
  882. self.server.ready.set()
  883. except OSError as e:
  884. if e.errno != RESET_ERROR:
  885. raise
  886. class ConfigSocketReceiver(ThreadingTCPServer):
  887. """
  888. A simple TCP socket-based logging config receiver.
  889. """
  890. allow_reuse_address = 1
  891. def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
  892. handler=None, ready=None, verify=None):
  893. ThreadingTCPServer.__init__(self, (host, port), handler)
  894. logging._acquireLock()
  895. self.abort = 0
  896. logging._releaseLock()
  897. self.timeout = 1
  898. self.ready = ready
  899. self.verify = verify
  900. def serve_until_stopped(self):
  901. import select
  902. abort = 0
  903. while not abort:
  904. rd, wr, ex = select.select([self.socket.fileno()],
  905. [], [],
  906. self.timeout)
  907. if rd:
  908. self.handle_request()
  909. logging._acquireLock()
  910. abort = self.abort
  911. logging._releaseLock()
  912. self.server_close()
  913. class Server(threading.Thread):
  914. def __init__(self, rcvr, hdlr, port, verify):
  915. super(Server, self).__init__()
  916. self.rcvr = rcvr
  917. self.hdlr = hdlr
  918. self.port = port
  919. self.verify = verify
  920. self.ready = threading.Event()
  921. def run(self):
  922. server = self.rcvr(port=self.port, handler=self.hdlr,
  923. ready=self.ready,
  924. verify=self.verify)
  925. if self.port == 0:
  926. self.port = server.server_address[1]
  927. self.ready.set()
  928. global _listener
  929. logging._acquireLock()
  930. _listener = server
  931. logging._releaseLock()
  932. server.serve_until_stopped()
  933. return Server(ConfigSocketReceiver, ConfigStreamHandler, port, verify)
  934. def stopListening():
  935. """
  936. Stop the listening server which was created with a call to listen().
  937. """
  938. global _listener
  939. logging._acquireLock()
  940. try:
  941. if _listener:
  942. _listener.abort = 1
  943. _listener = None
  944. finally:
  945. logging._releaseLock()