3
# This file is part of gunicorn released under the MIT license.
4
# See the NOTICE for more information.
6
# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved.
10
Configuration functions for the logging package for Python. The core package
11
is based on PEP 282 and comments thereto in comp.lang.python, and influenced
12
by Apache's log4j system.
14
Should work under Python versions >= 1.5.2, except that source line
15
information is not available unless 'sys._getframe()' is.
17
Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
19
To use, simply 'import logging' and log away!
22
import sys, logging, logging.handlers, string, socket, struct, os, traceback, types
30
from SocketServer import ThreadingTCPServer, StreamRequestHandler
33
DEFAULT_LOGGING_CONFIG_PORT = 9030
35
if sys.platform == "win32":
36
RESET_ERROR = 10054 #WSAECONNRESET
38
RESET_ERROR = 104 #ECONNRESET
41
# The following code implements a socket listener for on-the-fly
42
# reconfiguration of logging.
44
# _listener holds the server object doing the listening
47
def fileConfig(fname, defaults=None):
49
Read the logging configuration from a ConfigParser-format file.
51
This can be called several times from an application, allowing an end user
52
the ability to select from various pre-canned configurations (if the
53
developer provides a mechanism to present the choices and load the chosen
55
In versions of ConfigParser which have the readfp method [typically
56
shipped in 2.x versions of Python], you can pass in a file-like object
57
rather than a filename, in which case the file-like object will be read
62
cp = ConfigParser.ConfigParser(defaults)
63
if hasattr(cp, 'readfp') and hasattr(fname, 'readline'):
68
formatters = _create_formatters(cp)
71
logging._acquireLock()
73
logging._handlers.clear()
74
if hasattr(logging, '_handlerList'):
75
del logging._handlerList[:]
76
# Handlers add themselves to logging._handlers
77
handlers = _install_handlers(cp, formatters)
78
_install_loggers(cp, handlers)
80
logging._releaseLock()
84
"""Resolve a dotted name to a global object."""
85
name = string.split(name, '.')
87
found = __import__(used)
91
found = getattr(found, n)
92
except AttributeError:
94
found = getattr(found, n)
98
def _create_formatters(cp):
99
"""Create and return formatters"""
100
flist = cp.get("formatters", "keys")
103
flist = string.split(flist, ",")
106
form = string.strip(form)
107
sectname = "formatter_%s" % form
108
opts = cp.options(sectname)
110
fs = cp.get(sectname, "format", 1)
113
if "datefmt" in opts:
114
dfs = cp.get(sectname, "datefmt", 1)
117
c = logging.Formatter
119
class_name = cp.get(sectname, "class")
121
c = _resolve(class_name)
127
def _install_handlers(cp, formatters):
128
"""Install and return handlers"""
129
hlist = cp.get("handlers", "keys")
132
hlist = string.split(hlist, ",")
134
fixups = [] #for inter-handler references
136
hand = string.strip(hand)
137
sectname = "handler_%s" % hand
138
klass = cp.get(sectname, "class")
139
opts = cp.options(sectname)
140
if "formatter" in opts:
141
fmt = cp.get(sectname, "formatter")
145
klass = eval(klass, vars(logging))
146
except (AttributeError, NameError):
147
klass = _resolve(klass)
148
args = cp.get(sectname, "args")
149
args = eval(args, vars(logging))
150
h = apply(klass, args)
152
level = cp.get(sectname, "level")
153
h.setLevel(logging._levelNames[level])
155
h.setFormatter(formatters[fmt])
156
#temporary hack for FileHandler and MemoryHandler.
157
if klass == logging.handlers.MemoryHandler:
159
target = cp.get(sectname,"target")
162
if len(target): #the target handler may not be loaded yet, so keep for later...
163
fixups.append((h, target))
165
#now all handlers are loaded, fixup inter-handler references...
167
h.setTarget(handlers[t])
171
def _install_loggers(cp, handlers):
172
"""Create and install loggers"""
174
# configure the root first
175
llist = cp.get("loggers", "keys")
176
llist = string.split(llist, ",")
177
llist = map(lambda x: string.strip(x), llist)
179
sectname = "logger_root"
182
opts = cp.options(sectname)
184
level = cp.get(sectname, "level")
185
log.setLevel(logging._levelNames[level])
186
for h in root.handlers[:]:
187
root.removeHandler(h)
188
hlist = cp.get(sectname, "handlers")
190
hlist = string.split(hlist, ",")
192
log.addHandler(handlers[string.strip(hand)])
194
#and now the others...
195
#we don't want to lose the existing loggers,
196
#since other threads may have pointers to them.
197
#existing is set to contain all existing loggers,
198
#and as we go through the new configuration we
199
#remove any which are configured. At the end,
200
#what's left in existing is the set of loggers
201
#which were in the previous configuration but
202
#which are not in the new configuration.
203
existing = root.manager.loggerDict.keys()
204
#now set up the new ones...
206
sectname = "logger_%s" % log
207
qn = cp.get(sectname, "qualname")
208
opts = cp.options(sectname)
209
if "propagate" in opts:
210
propagate = cp.getint(sectname, "propagate")
213
logger = logging.getLogger(qn)
217
level = cp.get(sectname, "level")
218
logger.setLevel(logging._levelNames[level])
219
for h in logger.handlers[:]:
220
logger.removeHandler(h)
221
logger.propagate = propagate
223
hlist = cp.get(sectname, "handlers")
225
hlist = string.split(hlist, ",")
227
logger.addHandler(handlers[string.strip(hand)])
229
#Disable any old loggers. There's no point deleting
230
#them as other threads may continue to hold references
231
#and by disabling them, you stop them doing any logging.
233
root.manager.loggerDict[log].disabled = 1
236
def listen(port=DEFAULT_LOGGING_CONFIG_PORT):
238
Start up a socket server on the specified port, and listen for new
241
These will be sent as a file suitable for processing by fileConfig().
242
Returns a Thread object on which you can call start() to start the server,
243
and which you can join() when appropriate. To stop the server, call
247
raise NotImplementedError, "listen() needs threading to work"
249
class ConfigStreamHandler(StreamRequestHandler):
251
Handler for a logging configuration request.
253
It expects a completely new logging configuration and uses fileConfig
260
Each request is expected to be a 4-byte length, packed using
261
struct.pack(">L", n), followed by the config file.
262
Uses fileConfig() to do the grunt work.
266
conn = self.connection
269
slen = struct.unpack(">L", chunk)[0]
270
chunk = self.connection.recv(slen)
271
while len(chunk) < slen:
272
chunk = chunk + conn.recv(slen - len(chunk))
273
#Apply new configuration. We'd like to be able to
274
#create a StringIO and pass that in, but unfortunately
275
#1.5.2 ConfigParser does not support reading file
276
#objects, only actual files. So we create a temporary
277
#file and remove it later.
278
file = tempfile.mktemp(".ini")
284
except (KeyboardInterrupt, SystemExit):
287
traceback.print_exc()
289
except socket.error, e:
290
if type(e.args) != types.TupleType:
294
if errcode != RESET_ERROR:
297
class ConfigSocketReceiver(ThreadingTCPServer):
299
A simple TCP socket-based logging config receiver.
302
allow_reuse_address = 1
304
def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
306
ThreadingTCPServer.__init__(self, (host, port), handler)
307
logging._acquireLock()
309
logging._releaseLock()
312
def serve_until_stopped(self):
316
rd, wr, ex = select.select([self.socket.fileno()],
320
self.handle_request()
321
logging._acquireLock()
323
logging._releaseLock()
325
def serve(rcvr, hdlr, port):
326
server = rcvr(port=port, handler=hdlr)
328
logging._acquireLock()
330
logging._releaseLock()
331
server.serve_until_stopped()
333
return threading.Thread(target=serve,
334
args=(ConfigSocketReceiver,
335
ConfigStreamHandler, port))
339
Stop the listening server which was created with a call to listen().
343
logging._acquireLock()
346
logging._releaseLock()