This recipe adds logging support to SimpleXMLRPCServer using Python's logging module. The server will log the client IP, the client's XML request and the server's XML response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #!/usr/bin/env python
import SimpleXMLRPCServer
import logging
class LoggingSimpleXMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
"""Overides the default SimpleXMLRPCRequestHander to support logging. Logs
client IP and the XML request and response.
"""
def do_POST(self):
clientIP, port = self.client_address
# Log client IP and Port
logger.info('Client IP: %s - Port: %s' % (clientIP, port))
try:
# get arguments
data = self.rfile.read(int(self.headers["content-length"]))
# Log client request
logger.info('Client request: \n%s\n' % data)
response = self.server._marshaled_dispatch(
data, getattr(self, '_dispatch', None)
)
# Log server response
logger.info('Server response: \n%s\n' % response)
except: # This should only happen if the module is buggy
# internal error, report as HTTP server error
self.send_response(500)
self.end_headers()
else:
# got a valid XML RPC response
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.send_header("Content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
# shut down the connection
self.wfile.flush()
self.connection.shutdown(1)
class REMOTEMETHODS:
def hello(self, string):
return "Hello %s" % string
logger = logging.getLogger('xmlrpcserver')
hdlr = logging.FileHandler('xmlrpcserver.log')
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
XMLRPCServer = SimpleXMLRPCServer.SimpleXMLRPCServer(("",8080), LoggingSimpleXMLRPCRequestHandler)
object = REMOTEMETHODS()
XMLRPCServer.register_instance(object)
XMLRPCServer.serve_forever()
|
I initially came up with this recipe to log client connections to a file, but soon realized it would be helpful to log the XML requests and responses when trying to troubleshoot the XMLRPC client I was working on.
This has been tested with Python 2.4, but should work with Python 2.3.