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

该文章提供了一个Python函数,该函数将print语句的输出重定向到日志文件,便于后期查看和分析。通过创建一个名为Logger的类,实现了同时向终端和日志文件写入的功能。用户可以指定日志保存的路径和文件名,所有后续的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()

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值