在Python中维护多个线程的日志文件

时间:2013-08-16 18:31:06

标签: python python-multithreading

我有我的python baseHTTPServer服务器,它处理发布请求。 我使用了ThreadingMixIn,它现在为每个连接打开一个线程。 我希望做几个多线程的操作,例如: 1.监控成功/失败的连接活动,为每个活动添加1个计数器。 我需要一把锁。我的计数器位于同一文件的全局范围内。我怎样才能做到这一点? 2.我希望处理某种队列并将其写入文件,其中队列的内容是一组字符串,从我的不同线程写入,只是发送一些信息用于记录问题。怎么做到呢?我没有完成,因为我的线程是在“幕后”完成的,因为每次我在do_POST(..)方法中,我已经在不同的线程中。

Succcessful_Logins = 0
Failed_Logins = 0
LogsFile = open(logfile)

class httpHandler(BaseHTTPRequestHandler):

    def do_POST(self):
       ..

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    pass

server = ThreadingHTTPServer(('localhost', PORT_NUMBER), httpHandler)
server.serve_forever()

这是我的服务器的一个小脆弱。 困扰我的另一件事是我想先将回复发送回客户端,然后由于锁定机制或其他原因可能会延迟。

1 个答案:

答案 0 :(得分:0)

从您的代码中,看起来每个线程中都构建了一个新的httpHandler?如果是这种情况,您可以使用类变量进行计数,使用互斥锁来保护计数,如:

class httpHandler(...):
    # Note that these are class variables and are therefore accessable
    # to all instances
    numSuccess = 0
    numSuccessLock = new threading.Lock()

    def do_POST(self):
        self.numSuccessLock.aquire()
        self.numSuccess += 1
        self.numSuccessLock.release()

至于从不同的线程写入文件,有几个选项:

  1. 使用日志记录模块,“日志记录模块旨在保证线程安全,而无需客户完成任何特殊工作。”来自http://docs.python.org/2/library/logging.html#thread-safety
  2. 使用上述锁定对象序列化对文件的写入
  3. 使用线程安全队列排队写入,然后从队列中读取并从单独的线程写入文件。有关示例,请参阅http://docs.python.org/2/library/queue.html#module-Queue