defmake_print_to_file(path='./'):'''
A function to redirect print statements to a log file.
:param path: The path to the directory where the log file should be saved.
:return: None
'''import sys
import os
import datetime
classLogger(object):def__init__(self, filename="Default.log", path="./"):'''
:param filename: The name of the log file to be created.
:param path: The path to the directory where the log file should be saved.
'''
self.terminal = sys.stdout # terminal是标准输出,即print函数输出的位置
self.path= os.path.join(path, filename)# path是文件保存的路径
self.log_file =open(self.path,"a", encoding='utf8',)# log_file是文件对象,用于写入文件print("Saving logs to:", os.path.join(self.path, filename))# 打印日志保存的路径defwrite(self, message):'''
Writes the message to both the terminal and the log file.
:param message: The message to be written.
'''
self.terminal.write(message)# 将message写入到terminal,即标准输出
self.log_file.write(message)# 将message写入到log_file,即文件
self.log_file.flush()# 刷新缓存区,即将缓存区的内容写入到文件(这个地方一定要刷新,不然的话,文件中会没有内容)defflush(self):pass# Create a new log file with the current date as the filename
fileName = datetime.datetime.now().strftime('day'+'%Y_%m_%d')
sys.stdout = Logger(fileName +'.log', path=path)# Print a header to indicate that all subsequent print statements will be loggedprint("Logging started for:", fileName.center(60,'*'))# Return the logger objectreturn sys.stdout.log_file
if __name__ =='__main__':# Redirect print statements to a log file
log_file = make_print_to_file(path='./')# Any print statements after this point will be logged to the fileprint("1234124")print("--")# Close the log file
log_file.close()