How to have multi-threaded server log to one file ?

Stephen shriek at gmx.co.uk
Tue Feb 26 21:55:47 EST 2002


Consider a very simplistic server using the SocketServer module ~

import SocketServer

class MyServer(SocketServer.ThreadingTCPServer):
    allow_reuse_address = 1
    
class MyHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        # Do something interesting.
        # Log any errors <------------------------- HOW ? 

def start(host, port):
    server = MyServer((host, port), MyHandler)
    server.serve_forever() # serve forever
    

When the server is run, each request from a client is handled by
MyHandler() in a separate thread. If multiple requests are being run
at the same time, how should I write my code so that they cal all
write to the same log file without conflict ?  Should I use a global
variable for the logfile, as below ~

logfile = open("errors.log", "rw")

class MyServer(SocketServer.ThreadingTCPServer):
    allow_reuse_address = 1
    
class MyHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        # Do something interesting.
        global logfile
        logfile.write("fubar")


Or is there a more elegant solution that would take care of
concurrency ?
Is there a good document where I can learn how to do this in Python ? 

Thank you,

Stephen



More information about the Python-list mailing list