开发时使用日志框架,配置不好的话则产生一大堆日志问题,特别没有配置自动删除。
学习python时正好找找,东拼西凑的写了个脚本。
我这里日志配置的每天自动切分日志,形成1天1个日志文件夹(文件夹格式:YYYY-MM-DD),里面包含info,error日志。结构如下:
[sky@iZt4nip56cf5a8v01ya8z7Z testProj]$ ll
total 11616
drwxr-xr-x 3 root root 4096 Oct 9 00:05 2021-10-03
drwxr-xr-x 3 root root 4096 Oct 10 00:22 2021-10-04
drwxr-xr-x 3 root root 4096 Oct 11 00:04 2021-10-05
drwxr-xr-x 5 root root 4096 Oct 6 06:08 2021-10-06
drwxr-xr-x 4 root root 4096 Oct 7 04:05 2021-10-07
drwxr-xr-x 5 root root 4096 Oct 8 04:22 2021-10-08
drwxr-xr-x 5 root root 4096 Oct 9 06:27 2021-10-09
drwxr-xr-x 5 root root 4096 Oct 10 07:03 2021-10-10
drwxr-xr-x 5 root root 4096 Oct 11 06:38 2021-10-11
-rw-r--r-- 1 root root 2424510 Oct 11 15:23 error_log.log
-rw-r--r-- 1 root root 4540277 Oct 11 15:30 run_log.log
-rw-r--r-- 1 root root 4876445 Oct 11 15:17 warn_log.log
可以看到 testProj
下有很多日期命名的文件夹,
自动删除逻辑:例如自动删除7天以前的日志。
- 获取当前日期,并计算出前7天日期
now = datetime.datetime.now()
last7d = now - datetime.timedelta(days=days)
- 获取项目日志文件夹下文件列表
listdir = os.listdir(logDir)
- 遍历文件列表,获取文件名跟前7天日期比较。小于则删除
for d in listdir:
if d == 'run_log.log' or 'error_log.log' == d or 'warn_log.log' == d:
continue
try:
t = datetime.datetime.strptime(d, '%Y-%m-%d')
tdd = datetime.date(t.year, t.month, t.day)
if tdd < last7dd:
# 小于前7天日期,则删除。利用shutil.rmtree,迭代删除
logger.info('deleting {}'.format(logDir + '/' + d))
shutil.rmtree(logDir + '/' + d)
except BaseException as e:
# 防止存在其他文件导致文件名转日期报错
logger.exception(e)
这里用了第三方的日期框架loguru
使用时需要先安装
pip install loguru
可能会提示pip需要更新,根据提示先更新pip,再安装即可
完整代码:
import datetime
import os
import shutil
import sys, getopt
from loguru import logger
# definde logs base dir.
log_base_dir = 'logs/delete_old_log'
logger.add(log_base_dir + "/run_log.log", rotation='10MB', enqueue=True, encoding='utf-8', level='INFO', backtrace=True, diagnose=True)
logger.add(log_base_dir + "/error_log.log", rotation='10MB', enqueue=True, encoding='utf-8', level='ERROR', backtrace=True, diagnose=True)
def delete_dir(logDir, days):
"""
delete method.
------
Parameters
------------
logDir : str
log der
days: int
delete before days
"""
now = datetime.datetime.now()
last7d = now - datetime.timedelta(days=days)
last7dd = datetime.date(last7d.year, last7d.month, last7d.day)
logger.info('will delete {} dir'.format(last7dd))
listdir = os.listdir(logDir)
# logger.info(listdir)
for d in listdir:
if d == 'run_log.log' or 'error_log.log' == d or 'warn_log.log' == d:
continue
try:
t = datetime.datetime.strptime(d, '%Y-%m-%d')
tdd = datetime.date(t.year, t.month, t.day)
if tdd < last7dd:
logger.info('deleting {}'.format(logDir + '/' + d))
shutil.rmtree(logDir + '/' + d)
except BaseException as e:
logger.exception(e)
# logger.exception('process error, dir[{}], error info:{}'.format(d, e), e)
if __name__ == "__main__":
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:f:', ['days=', 'folder='])
logDir = '/home/skyjilygao/logs/testPorj'
days = 7
for opt_name, opt_value in opts:
if opt_name in ('-d', '--days'):
days = opt_value
continue
if opt_name in ('-f', '--folder'):
logDir = opt_value
continue
logger.info('config info. [folder={}, days={}]'.format(logDir, days))
logger.info('delete start...')
delete_dir(logDir, int(days))
except BaseException as e:
logger.exception('unknow error',e)
finally:
logger.info('delete end...')
相关源码见Github : delete_old_log_file