python3 将print打印的内容保存到日志

当你在Python中使用print函数时,通常会将输出显示在控制台上。但是,有时你可能希望将输出写入日志文件中,以便稍后进行查看和分析,而不需要每一次都要重新运行一下程序。

为了实现这个目的,可以编写一个函数,该函数将重定向print语句到日志文件中。以下是实现此功能的Python代码:

def make_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
 
    class Logger(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)) # 打印日志保存的路径
 
        def write(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() # 刷新缓存区,即将缓存区的内容写入到文件(这个地方一定要刷新,不然的话,文件中会没有内容)
 
        def flush(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 logged
    print("Logging started for:", fileName.center(60,'*'))

    # Return the logger object
    return 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 file
    print("1234124")
    print("--")
 
    # Close the log file
    log_file.close()
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值