gpt4 book ai didi

python - 日志记录在单独的线程中不起作用

转载 作者:太空狗 更新时间:2023-10-30 01:28:01 27 4
gpt4 key购买 nike

我有一个 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()

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

最佳答案

您确定这不是与日志记录无关的问题吗?以下简单脚本在 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 停止它。

关于python - 日志记录在单独的线程中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486400/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com