Python | print写入日志
有时我们需要将屏幕上打印的消息保存到一个文件中,如果每条信息都通过调用写入函数来实现,就太麻烦了
这里自己定义1个日志类,然后将 sys.stdout 设置为该类即可,非常方便
sys.stdout = Logger(fileName + '.log', path=path)
在主函数之前设置,之后调用系统的print 即可保存到 path 日志文件中。
在主函数之前生成日志对象 Logger
def make_print_to_file(path='./'):
'''
path, it is a path for save your log about fuction print
example:
use make_print_to_file() and the all the information of funtion print , will be write in to a log file
:return:
'''
import sys
import os
import sys
import datetime
class Logger(object):
def __init__(self, filename="Default.log", path="./"):
self.terminal = sys.stdout
self.path = os.path.join(path, filename)
self.log = open(self.path, "a", encoding='utf8', )
print("save:", os.path.join(self.path, filename))
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
fileName = datetime.datetime.now().strftime('day' + '%Y_%m_%d')
sys.stdout = Logger(fileName + '.log', path=path)
#############################################################
# 这里输出之后的所有的输出的print 内容即将写入日志
#############################################################
print(fileName.center(60, '*'))
if __name__ == '__main__':
make_print_to_file(path='./')
main()