记录不在单独的线程中工作

时间:2016-02-18 16:02:11

标签: python multithreading logging

我有一个python 2.5应用创建了一个单独的线程。我想登录到一个文件,我可以从主线程中执行此操作,但是当我从其他线程登录时它无法正常工作。

这发生在主线程上:

log_filename = os.path.join(os.path.dirname(__file__), "log", args[1]+'.log')
logging.basicConfig(filename=log_filename, level=logging.DEBUG)
logging.debug("Hello world!") # this works, line got written to a file

这是线程初始化的方式:

worker_thread = threading.Thread(target = MY_worker.MY_worker, args = tuple([task_queue]))
worker_thread.start()

现在从我正在执行的线程上运行的方法:

logging.debug("testing") # this doesnt got printed in the log file

我甚至尝试再次设置日志(在线程内部,就在写入日志之前):

log_filename = os.path.join(os.path.dirname(__file__), "log", 'sandbox.log')
logging.basicConfig(filename=log_filename, level=logging.DEBUG)
logging.debug("testing") # doesn't works neither.

我尝试直接写入文件,但它有效:

f = open(log_filename,'a')
f.write('some testing message \n')
f.close()

为什么会发生这种情况以及如何使其发挥作用?

1 个答案:

答案 0 :(得分:1)

您是否确定这不是与日志记录无关的问题?在Python 2.x和3.x下,以下普通脚本的行为与预期一样。

import logging
import threading
import time

def worker(arg):
    while not arg['stop']:
        logging.debug('Hi from myfunc')
        time.sleep(0.5)

def main():
    logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
    info = {'stop': False}
    thread = threading.Thread(target=worker, args=(info,))
    thread.start()
    while True:
        try:
            logging.debug('Hello from main')
            time.sleep(0.75)
        except KeyboardInterrupt:
            info['stop'] = True
            break
    thread.join()

if __name__ == '__main__':
    main()

运行时会生成

     0 Thread-1 Hi from myfunc
     1 MainThread Hello from main
   502 Thread-1 Hi from myfunc
   753 MainThread Hello from main
  1003 Thread-1 Hi from myfunc
  1504 Thread-1 Hi from myfunc
  1505 MainThread Hello from main
  2006 Thread-1 Hi from myfunc
  2255 MainThread Hello from main
  2507 Thread-1 Hi from myfunc
  3007 MainThread Hello from main
  3009 Thread-1 Hi from myfunc
  3510 Thread-1 Hi from myfunc
  3759 MainThread Hello from main
  4012 Thread-1 Hi from myfunc

直到我用Ctrl-C停止它。