/Lib/logging/config.py

http://unladen-swallow.googlecode.com/ · Python · 380 lines · 278 code · 16 blank · 86 comment · 29 complexity · 1c142d69f228e58c3555c5cbe3604dab MD5 · raw file

  1. # Copyright 2001-2007 by Vinay Sajip. All Rights Reserved.
  2. #
  3. # Permission to use, copy, modify, and distribute this software and its
  4. # documentation for any purpose and without fee is hereby granted,
  5. # provided that the above copyright notice appear in all copies and that
  6. # both that copyright notice and this permission notice appear in
  7. # supporting documentation, and that the name of Vinay Sajip
  8. # not be used in advertising or publicity pertaining to distribution
  9. # of the software without specific, written prior permission.
  10. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
  11. # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  12. # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
  13. # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  14. # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """
  17. Configuration functions for the logging package for Python. The core package
  18. is based on PEP 282 and comments thereto in comp.lang.python, and influenced
  19. by Apache's log4j system.
  20. Should work under Python versions >= 1.5.2, except that source line
  21. information is not available unless 'sys._getframe()' is.
  22. Copyright (C) 2001-2008 Vinay Sajip. All Rights Reserved.
  23. To use, simply 'import logging' and log away!
  24. """
  25. import sys, logging, logging.handlers, string, socket, struct, os, traceback, types
  26. try:
  27. import thread
  28. import threading
  29. except ImportError:
  30. thread = None
  31. from SocketServer import ThreadingTCPServer, StreamRequestHandler
  32. DEFAULT_LOGGING_CONFIG_PORT = 9030
  33. if sys.platform == "win32":
  34. RESET_ERROR = 10054 #WSAECONNRESET
  35. else:
  36. RESET_ERROR = 104 #ECONNRESET
  37. #
  38. # The following code implements a socket listener for on-the-fly
  39. # reconfiguration of logging.
  40. #
  41. # _listener holds the server object doing the listening
  42. _listener = None
  43. def fileConfig(fname, defaults=None, disable_existing_loggers=1):
  44. """
  45. Read the logging configuration from a ConfigParser-format file.
  46. This can be called several times from an application, allowing an end user
  47. the ability to select from various pre-canned configurations (if the
  48. developer provides a mechanism to present the choices and load the chosen
  49. configuration).
  50. In versions of ConfigParser which have the readfp method [typically
  51. shipped in 2.x versions of Python], you can pass in a file-like object
  52. rather than a filename, in which case the file-like object will be read
  53. using readfp.
  54. """
  55. import ConfigParser
  56. cp = ConfigParser.ConfigParser(defaults)
  57. if hasattr(cp, 'readfp') and hasattr(fname, 'readline'):
  58. cp.readfp(fname)
  59. else:
  60. cp.read(fname)
  61. formatters = _create_formatters(cp)
  62. # critical section
  63. logging._acquireLock()
  64. try:
  65. logging._handlers.clear()
  66. del logging._handlerList[:]
  67. # Handlers add themselves to logging._handlers
  68. handlers = _install_handlers(cp, formatters)
  69. _install_loggers(cp, handlers, disable_existing_loggers)
  70. finally:
  71. logging._releaseLock()
  72. def _resolve(name):
  73. """Resolve a dotted name to a global object."""
  74. name = string.split(name, '.')
  75. used = name.pop(0)
  76. found = __import__(used)
  77. for n in name:
  78. used = used + '.' + n
  79. try:
  80. found = getattr(found, n)
  81. except AttributeError:
  82. __import__(used)
  83. found = getattr(found, n)
  84. return found
  85. def _strip_spaces(alist):
  86. return map(lambda x: string.strip(x), alist)
  87. def _create_formatters(cp):
  88. """Create and return formatters"""
  89. flist = cp.get("formatters", "keys")
  90. if not len(flist):
  91. return {}
  92. flist = string.split(flist, ",")
  93. flist = _strip_spaces(flist)
  94. formatters = {}
  95. for form in flist:
  96. sectname = "formatter_%s" % form
  97. opts = cp.options(sectname)
  98. if "format" in opts:
  99. fs = cp.get(sectname, "format", 1)
  100. else:
  101. fs = None
  102. if "datefmt" in opts:
  103. dfs = cp.get(sectname, "datefmt", 1)
  104. else:
  105. dfs = None
  106. c = logging.Formatter
  107. if "class" in opts:
  108. class_name = cp.get(sectname, "class")
  109. if class_name:
  110. c = _resolve(class_name)
  111. f = c(fs, dfs)
  112. formatters[form] = f
  113. return formatters
  114. def _install_handlers(cp, formatters):
  115. """Install and return handlers"""
  116. hlist = cp.get("handlers", "keys")
  117. if not len(hlist):
  118. return {}
  119. hlist = string.split(hlist, ",")
  120. hlist = _strip_spaces(hlist)
  121. handlers = {}
  122. fixups = [] #for inter-handler references
  123. for hand in hlist:
  124. sectname = "handler_%s" % hand
  125. klass = cp.get(sectname, "class")
  126. opts = cp.options(sectname)
  127. if "formatter" in opts:
  128. fmt = cp.get(sectname, "formatter")
  129. else:
  130. fmt = ""
  131. try:
  132. klass = eval(klass, vars(logging))
  133. except (AttributeError, NameError):
  134. klass = _resolve(klass)
  135. args = cp.get(sectname, "args")
  136. args = eval(args, vars(logging))
  137. h = klass(*args)
  138. if "level" in opts:
  139. level = cp.get(sectname, "level")
  140. h.setLevel(logging._levelNames[level])
  141. if len(fmt):
  142. h.setFormatter(formatters[fmt])
  143. if issubclass(klass, logging.handlers.MemoryHandler):
  144. if "target" in opts:
  145. target = cp.get(sectname,"target")
  146. else:
  147. target = ""
  148. if len(target): #the target handler may not be loaded yet, so keep for later...
  149. fixups.append((h, target))
  150. handlers[hand] = h
  151. #now all handlers are loaded, fixup inter-handler references...
  152. for h, t in fixups:
  153. h.setTarget(handlers[t])
  154. return handlers
  155. def _install_loggers(cp, handlers, disable_existing_loggers):
  156. """Create and install loggers"""
  157. # configure the root first
  158. llist = cp.get("loggers", "keys")
  159. llist = string.split(llist, ",")
  160. llist = map(lambda x: string.strip(x), llist)
  161. llist.remove("root")
  162. sectname = "logger_root"
  163. root = logging.root
  164. log = root
  165. opts = cp.options(sectname)
  166. if "level" in opts:
  167. level = cp.get(sectname, "level")
  168. log.setLevel(logging._levelNames[level])
  169. for h in root.handlers[:]:
  170. root.removeHandler(h)
  171. hlist = cp.get(sectname, "handlers")
  172. if len(hlist):
  173. hlist = string.split(hlist, ",")
  174. hlist = _strip_spaces(hlist)
  175. for hand in hlist:
  176. log.addHandler(handlers[hand])
  177. #and now the others...
  178. #we don't want to lose the existing loggers,
  179. #since other threads may have pointers to them.
  180. #existing is set to contain all existing loggers,
  181. #and as we go through the new configuration we
  182. #remove any which are configured. At the end,
  183. #what's left in existing is the set of loggers
  184. #which were in the previous configuration but
  185. #which are not in the new configuration.
  186. existing = root.manager.loggerDict.keys()
  187. #The list needs to be sorted so that we can
  188. #avoid disabling child loggers of explicitly
  189. #named loggers. With a sorted list it is easier
  190. #to find the child loggers.
  191. existing.sort()
  192. #We'll keep the list of existing loggers
  193. #which are children of named loggers here...
  194. child_loggers = []
  195. #now set up the new ones...
  196. for log in llist:
  197. sectname = "logger_%s" % log
  198. qn = cp.get(sectname, "qualname")
  199. opts = cp.options(sectname)
  200. if "propagate" in opts:
  201. propagate = cp.getint(sectname, "propagate")
  202. else:
  203. propagate = 1
  204. logger = logging.getLogger(qn)
  205. if qn in existing:
  206. i = existing.index(qn)
  207. prefixed = qn + "."
  208. pflen = len(prefixed)
  209. num_existing = len(existing)
  210. i = i + 1 # look at the entry after qn
  211. while (i < num_existing) and (existing[i][:pflen] == prefixed):
  212. child_loggers.append(existing[i])
  213. i = i + 1
  214. existing.remove(qn)
  215. if "level" in opts:
  216. level = cp.get(sectname, "level")
  217. logger.setLevel(logging._levelNames[level])
  218. for h in logger.handlers[:]:
  219. logger.removeHandler(h)
  220. logger.propagate = propagate
  221. logger.disabled = 0
  222. hlist = cp.get(sectname, "handlers")
  223. if len(hlist):
  224. hlist = string.split(hlist, ",")
  225. hlist = _strip_spaces(hlist)
  226. for hand in hlist:
  227. logger.addHandler(handlers[hand])
  228. #Disable any old loggers. There's no point deleting
  229. #them as other threads may continue to hold references
  230. #and by disabling them, you stop them doing any logging.
  231. #However, don't disable children of named loggers, as that's
  232. #probably not what was intended by the user.
  233. for log in existing:
  234. logger = root.manager.loggerDict[log]
  235. if log in child_loggers:
  236. logger.level = logging.NOTSET
  237. logger.handlers = []
  238. logger.propagate = 1
  239. elif disable_existing_loggers:
  240. logger.disabled = 1
  241. def listen(port=DEFAULT_LOGGING_CONFIG_PORT):
  242. """
  243. Start up a socket server on the specified port, and listen for new
  244. configurations.
  245. These will be sent as a file suitable for processing by fileConfig().
  246. Returns a Thread object on which you can call start() to start the server,
  247. and which you can join() when appropriate. To stop the server, call
  248. stopListening().
  249. """
  250. if not thread:
  251. raise NotImplementedError, "listen() needs threading to work"
  252. class ConfigStreamHandler(StreamRequestHandler):
  253. """
  254. Handler for a logging configuration request.
  255. It expects a completely new logging configuration and uses fileConfig
  256. to install it.
  257. """
  258. def handle(self):
  259. """
  260. Handle a request.
  261. Each request is expected to be a 4-byte length, packed using
  262. struct.pack(">L", n), followed by the config file.
  263. Uses fileConfig() to do the grunt work.
  264. """
  265. import tempfile
  266. try:
  267. conn = self.connection
  268. chunk = conn.recv(4)
  269. if len(chunk) == 4:
  270. slen = struct.unpack(">L", chunk)[0]
  271. chunk = self.connection.recv(slen)
  272. while len(chunk) < slen:
  273. chunk = chunk + conn.recv(slen - len(chunk))
  274. #Apply new configuration. We'd like to be able to
  275. #create a StringIO and pass that in, but unfortunately
  276. #1.5.2 ConfigParser does not support reading file
  277. #objects, only actual files. So we create a temporary
  278. #file and remove it later.
  279. file = tempfile.mktemp(".ini")
  280. f = open(file, "w")
  281. f.write(chunk)
  282. f.close()
  283. try:
  284. fileConfig(file)
  285. except (KeyboardInterrupt, SystemExit):
  286. raise
  287. except:
  288. traceback.print_exc()
  289. os.remove(file)
  290. except socket.error, e:
  291. if type(e.args) != types.TupleType:
  292. raise
  293. else:
  294. errcode = e.args[0]
  295. if errcode != RESET_ERROR:
  296. raise
  297. class ConfigSocketReceiver(ThreadingTCPServer):
  298. """
  299. A simple TCP socket-based logging config receiver.
  300. """
  301. allow_reuse_address = 1
  302. def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
  303. handler=None):
  304. ThreadingTCPServer.__init__(self, (host, port), handler)
  305. logging._acquireLock()
  306. self.abort = 0
  307. logging._releaseLock()
  308. self.timeout = 1
  309. def serve_until_stopped(self):
  310. import select
  311. abort = 0
  312. while not abort:
  313. rd, wr, ex = select.select([self.socket.fileno()],
  314. [], [],
  315. self.timeout)
  316. if rd:
  317. self.handle_request()
  318. logging._acquireLock()
  319. abort = self.abort
  320. logging._releaseLock()
  321. def serve(rcvr, hdlr, port):
  322. server = rcvr(port=port, handler=hdlr)
  323. global _listener
  324. logging._acquireLock()
  325. _listener = server
  326. logging._releaseLock()
  327. server.serve_until_stopped()
  328. return threading.Thread(target=serve,
  329. args=(ConfigSocketReceiver,
  330. ConfigStreamHandler, port))
  331. def stopListening():
  332. """
  333. Stop the listening server which was created with a call to listen().
  334. """
  335. global _listener
  336. if _listener:
  337. logging._acquireLock()
  338. _listener.abort = 1
  339. _listener = None
  340. logging._releaseLock()