python线程记录和打印

时间:2018-12-31 12:26:42

标签: python multithreading logging

我有一个使用线程计时器启动多个进程的python脚本。它工作正常。但是,当我在过程结束时写打印或记录日志以检查状态时,控制台将开始打印奇怪的内容,如下所示:

short loop done
short loop done



long loop done



short loop done

空行来自哪里?

我正在使用这个intervall类来启动进程

class Interval(object):
"""Interface wrapper for re-occuring functions."""

def __init__(self, f, timeout):
    super(Interval, self).__init__()
    self.timeout = timeout
    self.fn = f
    self.next = None
    self.done = False
    self.setNext()


def setNext(self):
    """Queues up the next call to the intervaled function."""
    if not self.done:
        self.next = Timer(self.timeout, self.run)
        self.next.start()

    return self


def run(self):
    """Starts the interval."""
    self.fn()
    self.setNext()
    return self


def stop(self):
    """Stops the interval. Cancels any pending call."""
    self.done = True
    self.next.cancel()
    return self

和以下脚本启动所有内容

import IntervalClass
import logging
import sys

logging.basicConfig(level=logging.INFO,
                format='%(asctime)s %(name)-12s %(levelname)-8s % 
(message)s',
                datefmt='%m-%d %H:%M%S',
                filename='dbwrite.log',
                filemode='w')
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s % 
(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

logger1 = logging.getLogger('')

def long_functions():
    longFunction()
    logger1.info('long loop done')

def short_functions():
    shortFunction()
    logger1.info('short loop done')

long_loop = IntervalClass.Interval(longFunction, 45)
short_loop = IntervalClass.Interval(shortFunction, 25)

0 个答案:

没有答案