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

使用Python实现日志文件的定时清理和备份

发布时间:2024-01-08 19:39:33

在Python中,可以使用logging模块来实现日志文件的定时清理和备份。下面是一个使用logging模块的例子,包括定时清理和备份的功能。

import logging
import logging.handlers
import datetime

# 创建日志记录器
logger = logging.getLogger('example_logger')
logger.setLevel(logging.DEBUG)

# 创建文件处理器
log_file = 'example.log'
file_handler = logging.handlers.TimedRotatingFileHandler(log_file, when='midnight', backupCount=7)
file_handler.setLevel(logging.DEBUG)

# 创建格式化器
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)

# 将文件处理器添加到日志记录器
logger.addHandler(file_handler)

# 示例日志记录
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

# 定时清理日志文件
today = datetime.date.today()
one_week_ago = today - datetime.timedelta(days=7)
log_files = glob.glob('example.log*')  # 获取所有日志文件
for file in log_files:
    file_date = datetime.datetime.strptime(file.split('.')[1], '%Y-%m-%d').date()
    if file_date < one_week_ago:
        os.remove(file)  # 删除过期的日志文件

上述代码中,logging模块的getLogger函数用于获取一个日志记录器。logging.handlers.TimedRotatingFileHandler类用于创建一个按时间分割文件的文件处理器。when参数表示以什么时间单位分割文件,这里使用midnight表示每天的午夜分割文件。backupCount参数表示保留的备份文件的数量。

接下来,创建一个格式化器,用于指定日志的格式。代码中使用了%(asctime)s表示日志的时间,%(levelname)s表示日志的级别,%(message)s表示日志的内容。

然后,将文件处理器添加到日志记录器中。以上述配置为例,日志文件名为example.log,每天午夜会生成一个新的日志文件,并保留最近7个备份文件。

在示例中,logger记录了不同级别的日志,包括debuginfowarningerrorcritical。你可以根据自己的需求使用不同的日志级别。

最后,使用glob.glob方法获取所有的日志文件,然后使用datetime模块来比较文件的日期和一周前的日期。如果文件日期小于一周前的日期,则使用os.remove方法删除该文件。

这样,就实现了日志文件的定时清理和备份。你可以根据自己的需求修改参数和代码逻辑来满足你的要求。