我想在python中使用thread调用一个以logfile名称作为参数的函数

2024-06-25 23:14:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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条日志消息


Tags: selflogtargetdataloggingdefargsh1