欢迎访问宙启技术站
智能推送

文件操作日志:INFO级别的日志记录

发布时间:2023-12-16 06:35:37

文件操作日志是记录程序运行过程中对文件进行操作的日志信息,能够帮助开发人员在程序出现问题时快速定位和解决错误。在文件操作中,INFO级别的日志记录是比较常用的一种级别,用于记录一些正常的操作信息或者重要的状态变化。

以下是一个使用INFO级别日志记录文件操作的使用例子:

import logging

# 设置日志输出格式
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def create_file(file_name):
    try:
        # 在当前目录下创建文件
        with open(file_name, 'w') as file:
            file.write('This is a test file.')

        logging.info(f'Successfully created file: {file_name}')
    except Exception as e:
        logging.error(f'Failed to create file: {file_name} - {str(e)}')

def read_file(file_name):
    try:
        # 读取文件内容
        with open(file_name, 'r') as file:
            content = file.read()
            logging.info(f'Successfully read file: {file_name} - content: {content}')
    except FileNotFoundError:
        logging.error(f'File not found: {file_name}')
    except Exception as e:
        logging.error(f'Failed to read file: {file_name} - {str(e)}')

def update_file(file_name, new_content):
    try:
        # 更新文件内容
        with open(file_name, 'w') as file:
            file.write(new_content)
            logging.info(f'Successfully updated file: {file_name} - new content: {new_content}')
    except FileNotFoundError:
        logging.error(f'File not found: {file_name}')
    except Exception as e:
        logging.error(f'Failed to update file: {file_name} - {str(e)}')

def delete_file(file_name):
    try:
        # 删除文件
        os.remove(file_name)
        logging.info(f'Successfully deleted file: {file_name}')
    except FileNotFoundError:
        logging.error(f'File not found: {file_name}')
    except Exception as e:
        logging.error(f'Failed to delete file: {file_name} - {str(e)}')

if __name__ == '__main__':
    file_name = 'test.txt'

    create_file(file_name)
    read_file(file_name)
    update_file(file_name, 'This is an updated test file.')
    read_file(file_name)
    delete_file(file_name)

在上述例子中,首先我们通过logging.basicConfig()函数设置了日志输出的级别为INFO,并定义了日志的输出格式,其中%(asctime)s代表日志记录时间,%(levelname)s代表日志级别,%(message)s代表日志消息。

然后,我们定义了四个文件操作函数:create_file()read_file()update_file()delete_file()。在每个函数中,我们进行了相应的文件操作,并使用logging.info()函数记录了操作结果。

最后,我们通过调用这四个文件操作函数来测试文件的创建、读取、更新和删除功能,并通过日志信息来查看操作结果。如果某个操作出现错误,会记录下错误信息,并显示错误类型和具体的错误原因。

例如,当我们运行这段代码时,会得到如下输出:

2022-07-14 10:00:00 - INFO - Successfully created file: test.txt
2022-07-14 10:00:01 - INFO - Successfully read file: test.txt - content: This is a test file.
2022-07-14 10:00:02 - INFO - Successfully updated file: test.txt - new content: This is an updated test file.
2022-07-14 10:00:03 - INFO - Successfully read file: test.txt - content: This is an updated test file.
2022-07-14 10:00:04 - INFO - Successfully deleted file: test.txt

从以上输出可以看出,文件的创建、读取、更新和删除操作都成功执行,并且通过INFO级别的日志记录了相应的操作信息。这些日志信息可以帮助我们追踪程序的执行过程,找出错误的原因,并进行及时的修复。