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