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