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

Jason Orendorff jason at jorendorff.com
Thu Feb 28 00:07:58 EST 2002


Stephen wrote:
> [...] how do I get the same Queue object into both MyHandler and
> MyServer in the first place ? [...] Or is this somewhere that a
> global variable Queue object should be used ?

Try making a separate module that says:

---------------------------------------------------------------
# logging.py - used by everyone else that needs to log messages

import Queue

# This is the queue object that's used to hold log events.
# LoggingThread knows about it, and the log() function below
# knows about it.  No one else is allowed to see it.
_log_queue = Queue.Queue()

class LoggingThread:
    ...
    def run(self):
        while 1:
            message = _log_queue.get()
            self.logfile.write(message + '\n')  # (or whatever)

# Kick off the logging thread.
LoggingThread().start()

def log(msg):
    _log_queue.put(msg)

---------------------------------------------------------------

Then your MyHandler and MyServer code can just use the log()
function, like this:

  from logging import log
  ...
  ...
  log("Something happened")
  ...

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list