# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved.
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Configuration functions for the logging package for Python. The core package
is based on PEP 282 and comments thereto in comp.lang.python, and influenced
by Apache's log4j system.
Should work under Python versions >= 1.5.2, except that source line
information is not available unless 'sys._getframe()' is.
Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away!
import sys
, logging
, logging
.handlers
, string
, socket
, struct
, os
, traceback
from SocketServer
import ThreadingTCPServer
, StreamRequestHandler
DEFAULT_LOGGING_CONFIG_PORT
= 9030
if sys
.platform
== "win32":
RESET_ERROR
= 10054 #WSAECONNRESET
RESET_ERROR
= 104 #ECONNRESET
# The following code implements a socket listener for on-the-fly
# reconfiguration of logging.
# _listener holds the server object doing the listening
def fileConfig(fname
, defaults
=None):
Read the logging configuration from a ConfigParser-format file.
This can be called several times from an application, allowing an end user
the ability to select from various pre-canned configurations (if the
developer provides a mechanism to present the choices and load the chosen
In versions of ConfigParser which have the readfp method [typically
shipped in 2.x versions of Python], you can pass in a file-like object
rather than a filename, in which case the file-like object will be read
cp
= ConfigParser
.ConfigParser(defaults
)
if hasattr(cp
, 'readfp') and hasattr(fname
, 'readline'):
#first, do the formatters...
flist
= cp
.get("formatters", "keys")
flist
= string
.split(flist
, ",")
sectname
= "formatter_%s" % form
opts
= cp
.options(sectname
)
fs
= cp
.get(sectname
, "format", 1)
dfs
= cp
.get(sectname
, "datefmt", 1)
f
= logging
.Formatter(fs
, dfs
)
#next, do the handlers...
#first, lose the existing handlers...
logging
._handlers
.clear()
#now set up the new ones...
hlist
= cp
.get("handlers", "keys")
hlist
= string
.split(hlist
, ",")
fixups
= [] #for inter-handler references
sectname
= "handler_%s" % hand
klass
= cp
.get(sectname
, "class")
opts
= cp
.options(sectname
)
fmt
= cp
.get(sectname
, "formatter")
klass
= eval(klass
, vars(logging
))
args
= cp
.get(sectname
, "args")
args
= eval(args
, vars(logging
))
level
= cp
.get(sectname
, "level")
h
.setLevel(logging
._levelNames
[level
])
h
.setFormatter(formatters
[fmt
])
#temporary hack for FileHandler and MemoryHandler.
if klass
== logging
.handlers
.MemoryHandler
:
target
= cp
.get(sectname
,"target")
if len(target
): #the target handler may not be loaded yet, so keep for later...
fixups
.append((h
, target
))
except: #if an error occurs when instantiating a handler, too bad
pass #this could happen e.g. because of lack of privileges
#now all handlers are loaded, fixup inter-handler references...
#at last, the loggers...first the root...
llist
= cp
.get("loggers", "keys")
llist
= string
.split(llist
, ",")
opts
= cp
.options(sectname
)
level
= cp
.get(sectname
, "level")
log
.setLevel(logging
._levelNames
[level
])
for h
in root
.handlers
[:]:
hlist
= cp
.get(sectname
, "handlers")
hlist
= string
.split(hlist
, ",")
log
.addHandler(handlers
[hand
])
#we don't want to lose the existing loggers,
#since other threads may have pointers to them.
#existing is set to contain all existing loggers,
#and as we go through the new configuration we
#remove any which are configured. At the end,
#what's left in existing is the set of loggers
#which were in the previous configuration but
#which are not in the new configuration.
existing
= root
.manager
.loggerDict
.keys()
#now set up the new ones...
sectname
= "logger_%s" % log
qn
= cp
.get(sectname
, "qualname")
opts
= cp
.options(sectname
)
propagate
= cp
.getint(sectname
, "propagate")
logger
= logging
.getLogger(qn
)
level
= cp
.get(sectname
, "level")
logger
.setLevel(logging
._levelNames
[level
])
for h
in logger
.handlers
[:]:
logger
.propagate
= propagate
hlist
= cp
.get(sectname
, "handlers")
hlist
= string
.split(hlist
, ",")
logger
.addHandler(handlers
[hand
])
#Disable any old loggers. There's no point deleting
#them as other threads may continue to hold references
#and by disabling them, you stop them doing any logging.
root
.manager
.loggerDict
[log
].disabled
= 1
traceback
.print_exception(ei
[0], ei
[1], ei
[2], None, sys
.stderr
)
def listen(port
=DEFAULT_LOGGING_CONFIG_PORT
):
Start up a socket server on the specified port, and listen for new
These will be sent as a file suitable for processing by fileConfig().
Returns a Thread object on which you can call start() to start the server,
and which you can join() when appropriate. To stop the server, call
raise NotImplementedError, "listen() needs threading to work"
class ConfigStreamHandler(StreamRequestHandler
):
Handler for a logging configuration request.
It expects a completely new logging configuration and uses fileConfig
Each request is expected to be a 4-byte length, packed using
struct.pack(">L", n), followed by the config file.
Uses fileConfig() to do the grunt work.
slen
= struct
.unpack(">L", chunk
)[0]
chunk
= self
.connection
.recv(slen
)
chunk
= chunk
+ conn
.recv(slen
- len(chunk
))
#Apply new configuration. We'd like to be able to
#create a StringIO and pass that in, but unfortunately
#1.5.2 ConfigParser does not support reading file
#objects, only actual files. So we create a temporary
#file and remove it later.
file = tempfile
.mktemp(".ini")
if type(e
.args
) != types
.TupleType
:
if errcode
!= RESET_ERROR
:
class ConfigSocketReceiver(ThreadingTCPServer
):
A simple TCP socket-based logging config receiver.
def __init__(self
, host
='localhost', port
=DEFAULT_LOGGING_CONFIG_PORT
,
ThreadingTCPServer
.__init
__(self
, (host
, port
), handler
)
def serve_until_stopped(self
):
rd
, wr
, ex
= select
.select([self
.socket
.fileno()],
def serve(rcvr
, hdlr
, port
):
server
= rcvr(port
=port
, handler
=hdlr
)
server
.serve_until_stopped()
return threading
.Thread(target
=serve
,
args
=(ConfigSocketReceiver
,
ConfigStreamHandler
, port
))
Stop the listening server which was created with a call to listen().