0
import threading
import logging, logging.handlers


class FuncThread(threading.Thread):
    def __init__(self, target, *args):
        self._target = target
        self._args = args
        threading.Thread.__init__(self)

    def run(self):
        self._target(*self._args)

def someOtherFunc(data, key, testlogfile):
    #initialize logging system
    testlogger = logging.getLogger("testlogger")
    testlogger.setLevel(logging.DEBUG)
    file = open(testlogfile,'w')
    file.close()
    # This handler writes everything to a file.
    h1 = logging.FileHandler(testlogfile)
    f = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
    h1.setFormatter(f)
    h1.setLevel(logging.DEBUG)
    testlogger.addHandler(h1)
    testlogger = logging.getLogger("testlogger")
    testlogger.debug("someOtherFunc was called : data=%s; key=%s" % (str(data), str(key)))

t1 = FuncThread(someOtherFunc, [1,2], 4, "output1.log")
t1.start()
t1.join()

t2 = FuncThread(someOtherFunc, [2,4], 8, "output2.log")
t2.start()
t2.join()

t3 = FuncThread(someOtherFunc, [3,6], 9, "output3.log")
t3.start()
t3.join()

上面的问题是 output1.log 为所有 t1、t2 和 t3 线程记录了 3 条日志消息。我希望 output1.log 分别只有 t1 线程日志和

4

1 回答 1

0

在这一行:

testlogger = logging.getLogger("testlogger")

每个线程都获取相同的记录器。尝试将其更改为:

testlogger = logging.getLogger(testlogfile)
于 2013-09-11T20:56:20.367 回答