[英]How to redirect python logging output to file instead of stdout?
我想重定向所有输出,甚至是从导入到文件的外部模块中重定向。
sys.stdout = open('logfile', 'a')
在标准输出上回显外部文件所做的日志记录不起作用。
我已经修改了外部模块的源代码,并且它们与python的“ logging”模块紧密结合,并依赖于它的输出。
另外,我也不想使用>运算符使用流重定向。
尝试这个:
sysstdout = sys.stdout
log_file = open("your_log_file.txt","w")
sys.stdout = log_file
print("this will be written to message.log")
sys.stdout = sysstdout
log_file.close()
或者,做正确的事并正确使用Python的日志记录模块 。
import sys
sys.stdout = sys.stderr = open('logfile', 'a')
print('this should be working from anywhere')
import logging
logging.warn('this too')
您看到外部模块打印到控制台的原因可能是它们正在使用stderr
(这是logging
模块的默认输出处理程序)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.