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线程日志和
答案 0 :(得分:0)
在这一行:
testlogger = logging.getLogger("testlogger")
每个线程都获得相同的记录器。尝试将其更改为:
testlogger = logging.getLogger(testlogfile)