blob: 50bacdb3e48bccf55ff6cccf80e2b13ec92d9735 [file] [log] [blame]
Vinay Sajip95dd03b2007-11-11 14:27:30 +00001# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved.
Guido van Rossum57102f82002-11-13 16:15:58 +00002#
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 Rossum57102f82002-11-13 16:15:58 +000016
17"""
Vinay Sajip3f742842004-02-28 16:07:46 +000018Configuration functions for the logging package for Python. The core package
19is based on PEP 282 and comments thereto in comp.lang.python, and influenced
20by Apache's log4j system.
Guido van Rossum57102f82002-11-13 16:15:58 +000021
22Should work under Python versions >= 1.5.2, except that source line
Vinay Sajip326441e2004-02-20 13:16:36 +000023information is not available unless 'sys._getframe()' is.
Guido van Rossum57102f82002-11-13 16:15:58 +000024
Vinay Sajip95dd03b2007-11-11 14:27:30 +000025Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved.
Guido van Rossum57102f82002-11-13 16:15:58 +000026
27To use, simply 'import logging' and log away!
28"""
29
Georg Brandl4e933132006-09-06 20:05:58 +000030import sys, logging, logging.handlers, string, socket, struct, os, traceback, types
Vinay Sajip612df8e2005-02-18 11:54:46 +000031
32try:
33 import thread
34 import threading
35except ImportError:
36 thread = None
Guido van Rossum57102f82002-11-13 16:15:58 +000037
Georg Brandle152a772008-05-24 18:31:28 +000038from SocketServer import ThreadingTCPServer, StreamRequestHandler
Guido van Rossum57102f82002-11-13 16:15:58 +000039
40
41DEFAULT_LOGGING_CONFIG_PORT = 9030
42
Vinay Sajip326441e2004-02-20 13:16:36 +000043if sys.platform == "win32":
44 RESET_ERROR = 10054 #WSAECONNRESET
45else:
46 RESET_ERROR = 104 #ECONNRESET
47
Guido van Rossum57102f82002-11-13 16:15:58 +000048#
49# The following code implements a socket listener for on-the-fly
50# reconfiguration of logging.
51#
52# _listener holds the server object doing the listening
53_listener = None
54
Vinay Sajip5f7b97d2008-06-19 22:40:17 +000055def fileConfig(fname, defaults=None, disable_existing_loggers=1):
Guido van Rossum57102f82002-11-13 16:15:58 +000056 """
57 Read the logging configuration from a ConfigParser-format file.
58
59 This can be called several times from an application, allowing an end user
60 the ability to select from various pre-canned configurations (if the
61 developer provides a mechanism to present the choices and load the chosen
62 configuration).
63 In versions of ConfigParser which have the readfp method [typically
64 shipped in 2.x versions of Python], you can pass in a file-like object
65 rather than a filename, in which case the file-like object will be read
66 using readfp.
67 """
Georg Brandl392c6fc2008-05-25 07:25:25 +000068 import ConfigParser
Guido van Rossum57102f82002-11-13 16:15:58 +000069
Georg Brandl392c6fc2008-05-25 07:25:25 +000070 cp = ConfigParser.ConfigParser(defaults)
Guido van Rossum57102f82002-11-13 16:15:58 +000071 if hasattr(cp, 'readfp') and hasattr(fname, 'readline'):
72 cp.readfp(fname)
73 else:
74 cp.read(fname)
Vinay Sajip989b69a2006-01-16 21:28:37 +000075
76 formatters = _create_formatters(cp)
77
78 # critical section
Guido van Rossum57102f82002-11-13 16:15:58 +000079 logging._acquireLock()
80 try:
Vinay Sajip989b69a2006-01-16 21:28:37 +000081 logging._handlers.clear()
Georg Brandlf3e30422006-08-12 08:32:02 +000082 del logging._handlerList[:]
Vinay Sajip989b69a2006-01-16 21:28:37 +000083 # Handlers add themselves to logging._handlers
84 handlers = _install_handlers(cp, formatters)
Vinay Sajip5f7b97d2008-06-19 22:40:17 +000085 _install_loggers(cp, handlers, disable_existing_loggers)
Guido van Rossum57102f82002-11-13 16:15:58 +000086 finally:
87 logging._releaseLock()
88
Vinay Sajip989b69a2006-01-16 21:28:37 +000089
Vinay Sajip7a7160b2006-01-20 18:28:03 +000090def _resolve(name):
91 """Resolve a dotted name to a global object."""
92 name = string.split(name, '.')
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
104
Vinay Sajip989b69a2006-01-16 21:28:37 +0000105def _create_formatters(cp):
106 """Create and return formatters"""
107 flist = cp.get("formatters", "keys")
108 if not len(flist):
109 return {}
110 flist = string.split(flist, ",")
111 formatters = {}
112 for form in flist:
Vinay Sajip66a17262006-12-11 14:26:23 +0000113 sectname = "formatter_%s" % string.strip(form)
Vinay Sajip989b69a2006-01-16 21:28:37 +0000114 opts = cp.options(sectname)
115 if "format" in opts:
116 fs = cp.get(sectname, "format", 1)
117 else:
118 fs = None
119 if "datefmt" in opts:
120 dfs = cp.get(sectname, "datefmt", 1)
121 else:
122 dfs = None
Vinay Sajip7a7160b2006-01-20 18:28:03 +0000123 c = logging.Formatter
124 if "class" in opts:
125 class_name = cp.get(sectname, "class")
126 if class_name:
127 c = _resolve(class_name)
128 f = c(fs, dfs)
Vinay Sajip989b69a2006-01-16 21:28:37 +0000129 formatters[form] = f
130 return formatters
131
132
133def _install_handlers(cp, formatters):
134 """Install and return handlers"""
135 hlist = cp.get("handlers", "keys")
136 if not len(hlist):
137 return {}
138 hlist = string.split(hlist, ",")
139 handlers = {}
140 fixups = [] #for inter-handler references
141 for hand in hlist:
Vinay Sajip66a17262006-12-11 14:26:23 +0000142 sectname = "handler_%s" % string.strip(hand)
Vinay Sajip989b69a2006-01-16 21:28:37 +0000143 klass = cp.get(sectname, "class")
144 opts = cp.options(sectname)
145 if "formatter" in opts:
146 fmt = cp.get(sectname, "formatter")
147 else:
148 fmt = ""
149 klass = eval(klass, vars(logging))
150 args = cp.get(sectname, "args")
151 args = eval(args, vars(logging))
152 h = apply(klass, args)
153 if "level" in opts:
154 level = cp.get(sectname, "level")
155 h.setLevel(logging._levelNames[level])
156 if len(fmt):
157 h.setFormatter(formatters[fmt])
Vinay Sajip5ff71712008-06-29 21:25:28 +0000158 if issubclass(klass, logging.handlers.MemoryHandler):
Vinay Sajip989b69a2006-01-16 21:28:37 +0000159 if "target" in opts:
160 target = cp.get(sectname,"target")
161 else:
162 target = ""
163 if len(target): #the target handler may not be loaded yet, so keep for later...
164 fixups.append((h, target))
165 handlers[hand] = h
166 #now all handlers are loaded, fixup inter-handler references...
167 for h, t in fixups:
168 h.setTarget(handlers[t])
169 return handlers
170
171
Vinay Sajip5f7b97d2008-06-19 22:40:17 +0000172def _install_loggers(cp, handlers, disable_existing_loggers):
Vinay Sajip989b69a2006-01-16 21:28:37 +0000173 """Create and install loggers"""
174
175 # configure the root first
176 llist = cp.get("loggers", "keys")
177 llist = string.split(llist, ",")
Vinay Sajip66a17262006-12-11 14:26:23 +0000178 llist = map(lambda x: string.strip(x), llist)
Vinay Sajip989b69a2006-01-16 21:28:37 +0000179 llist.remove("root")
180 sectname = "logger_root"
181 root = logging.root
182 log = root
183 opts = cp.options(sectname)
184 if "level" in opts:
185 level = cp.get(sectname, "level")
186 log.setLevel(logging._levelNames[level])
187 for h in root.handlers[:]:
188 root.removeHandler(h)
189 hlist = cp.get(sectname, "handlers")
190 if len(hlist):
191 hlist = string.split(hlist, ",")
192 for hand in hlist:
Vinay Sajip66a17262006-12-11 14:26:23 +0000193 log.addHandler(handlers[string.strip(hand)])
Vinay Sajip989b69a2006-01-16 21:28:37 +0000194
195 #and now the others...
196 #we don't want to lose the existing loggers,
197 #since other threads may have pointers to them.
198 #existing is set to contain all existing loggers,
199 #and as we go through the new configuration we
200 #remove any which are configured. At the end,
201 #what's left in existing is the set of loggers
202 #which were in the previous configuration but
203 #which are not in the new configuration.
204 existing = root.manager.loggerDict.keys()
Vinay Sajip95dd03b2007-11-11 14:27:30 +0000205 #The list needs to be sorted so that we can
206 #avoid disabling child loggers of explicitly
207 #named loggers. With a sorted list it is easier
208 #to find the child loggers.
209 existing.sort()
210 #We'll keep the list of existing loggers
211 #which are children of named loggers here...
212 child_loggers = []
Vinay Sajip989b69a2006-01-16 21:28:37 +0000213 #now set up the new ones...
214 for log in llist:
215 sectname = "logger_%s" % log
216 qn = cp.get(sectname, "qualname")
217 opts = cp.options(sectname)
218 if "propagate" in opts:
219 propagate = cp.getint(sectname, "propagate")
220 else:
221 propagate = 1
222 logger = logging.getLogger(qn)
223 if qn in existing:
Vinay Sajip95dd03b2007-11-11 14:27:30 +0000224 i = existing.index(qn)
225 prefixed = qn + "."
226 pflen = len(prefixed)
227 num_existing = len(existing)
228 i = i + 1 # look at the entry after qn
229 while (i < num_existing) and (existing[i][:pflen] == prefixed):
230 child_loggers.append(existing[i])
231 i = i + 1
Vinay Sajip989b69a2006-01-16 21:28:37 +0000232 existing.remove(qn)
233 if "level" in opts:
234 level = cp.get(sectname, "level")
235 logger.setLevel(logging._levelNames[level])
236 for h in logger.handlers[:]:
237 logger.removeHandler(h)
238 logger.propagate = propagate
239 logger.disabled = 0
240 hlist = cp.get(sectname, "handlers")
241 if len(hlist):
242 hlist = string.split(hlist, ",")
243 for hand in hlist:
Vinay Sajip66a17262006-12-11 14:26:23 +0000244 logger.addHandler(handlers[string.strip(hand)])
Vinay Sajip989b69a2006-01-16 21:28:37 +0000245
246 #Disable any old loggers. There's no point deleting
247 #them as other threads may continue to hold references
248 #and by disabling them, you stop them doing any logging.
Vinay Sajip95dd03b2007-11-11 14:27:30 +0000249 #However, don't disable children of named loggers, as that's
250 #probably not what was intended by the user.
Vinay Sajip989b69a2006-01-16 21:28:37 +0000251 for log in existing:
Vinay Sajip95dd03b2007-11-11 14:27:30 +0000252 logger = root.manager.loggerDict[log]
253 if log in child_loggers:
254 logger.level = logging.NOTSET
255 logger.handlers = []
256 logger.propagate = 1
Vinay Sajip5f7b97d2008-06-19 22:40:17 +0000257 elif disable_existing_loggers:
Vinay Sajip95dd03b2007-11-11 14:27:30 +0000258 logger.disabled = 1
Vinay Sajip989b69a2006-01-16 21:28:37 +0000259
260
Guido van Rossum57102f82002-11-13 16:15:58 +0000261def listen(port=DEFAULT_LOGGING_CONFIG_PORT):
262 """
263 Start up a socket server on the specified port, and listen for new
264 configurations.
265
266 These will be sent as a file suitable for processing by fileConfig().
267 Returns a Thread object on which you can call start() to start the server,
268 and which you can join() when appropriate. To stop the server, call
269 stopListening().
270 """
271 if not thread:
272 raise NotImplementedError, "listen() needs threading to work"
273
274 class ConfigStreamHandler(StreamRequestHandler):
275 """
276 Handler for a logging configuration request.
277
278 It expects a completely new logging configuration and uses fileConfig
279 to install it.
280 """
281 def handle(self):
282 """
283 Handle a request.
284
Vinay Sajip4c1423b2005-06-05 20:39:36 +0000285 Each request is expected to be a 4-byte length, packed using
286 struct.pack(">L", n), followed by the config file.
287 Uses fileConfig() to do the grunt work.
Guido van Rossum57102f82002-11-13 16:15:58 +0000288 """
289 import tempfile
290 try:
291 conn = self.connection
292 chunk = conn.recv(4)
293 if len(chunk) == 4:
294 slen = struct.unpack(">L", chunk)[0]
295 chunk = self.connection.recv(slen)
296 while len(chunk) < slen:
297 chunk = chunk + conn.recv(slen - len(chunk))
298 #Apply new configuration. We'd like to be able to
299 #create a StringIO and pass that in, but unfortunately
300 #1.5.2 ConfigParser does not support reading file
301 #objects, only actual files. So we create a temporary
302 #file and remove it later.
303 file = tempfile.mktemp(".ini")
304 f = open(file, "w")
305 f.write(chunk)
306 f.close()
Vinay Sajip989b69a2006-01-16 21:28:37 +0000307 try:
308 fileConfig(file)
309 except (KeyboardInterrupt, SystemExit):
310 raise
311 except:
312 traceback.print_exc()
Guido van Rossum57102f82002-11-13 16:15:58 +0000313 os.remove(file)
314 except socket.error, e:
315 if type(e.args) != types.TupleType:
316 raise
317 else:
318 errcode = e.args[0]
319 if errcode != RESET_ERROR:
320 raise
321
322 class ConfigSocketReceiver(ThreadingTCPServer):
323 """
324 A simple TCP socket-based logging config receiver.
325 """
326
327 allow_reuse_address = 1
328
329 def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
Neal Norwitzc4d047a2002-11-15 23:33:20 +0000330 handler=None):
Guido van Rossum57102f82002-11-13 16:15:58 +0000331 ThreadingTCPServer.__init__(self, (host, port), handler)
332 logging._acquireLock()
333 self.abort = 0
334 logging._releaseLock()
335 self.timeout = 1
336
337 def serve_until_stopped(self):
338 import select
339 abort = 0
340 while not abort:
341 rd, wr, ex = select.select([self.socket.fileno()],
342 [], [],
343 self.timeout)
344 if rd:
345 self.handle_request()
346 logging._acquireLock()
347 abort = self.abort
348 logging._releaseLock()
349
Neal Norwitzc4d047a2002-11-15 23:33:20 +0000350 def serve(rcvr, hdlr, port):
351 server = rcvr(port=port, handler=hdlr)
Guido van Rossum57102f82002-11-13 16:15:58 +0000352 global _listener
353 logging._acquireLock()
354 _listener = server
355 logging._releaseLock()
356 server.serve_until_stopped()
357
Neal Norwitzc4d047a2002-11-15 23:33:20 +0000358 return threading.Thread(target=serve,
359 args=(ConfigSocketReceiver,
360 ConfigStreamHandler, port))
Guido van Rossum57102f82002-11-13 16:15:58 +0000361
362def stopListening():
363 """
364 Stop the listening server which was created with a call to listen().
365 """
Neal Norwitzc4d047a2002-11-15 23:33:20 +0000366 global _listener
Guido van Rossum57102f82002-11-13 16:15:58 +0000367 if _listener:
368 logging._acquireLock()
369 _listener.abort = 1
370 _listener = None
371 logging._releaseLock()