Arn*_*Roa 5 python logging multithreading
我有一个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
Run Code Online (Sandbox Code Playgroud)
这是线程初始化的方式:
worker_thread = threading.Thread(target = MY_worker.MY_worker, args = tuple([task_queue]))
worker_thread.start()
Run Code Online (Sandbox Code Playgroud)
现在从我正在做的线程上运行的方法:
logging.debug("testing") # this doesnt got printed in the log file
Run Code Online (Sandbox Code Playgroud)
我甚至尝试再次设置日志(在线程内部,在写入日志之前):
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.
Run Code Online (Sandbox Code Playgroud)
我尝试直接写入文件,它工作:
f = open(log_filename,'a')
f.write('some testing message \n')
f.close()
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况以及如何使其发挥作用?
您确定这不是与日志记录无关的问题吗?以下简单脚本在 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()
Run Code Online (Sandbox Code Playgroud)
运行时,它会产生
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
Run Code Online (Sandbox Code Playgroud)
直到我用 Ctrl-C 停止它。