nginx 日志分割的脚本
时间: 2023-05-24 15:03:07 浏览: 63
A:
下面是一个简单的Python脚本,可以将Nginx访问日志按照日期分割成不同的日志文件。
```python
import os
import re
import datetime
log_dir = '/var/log/nginx'
log_file = 'access.log'
def get_current_date():
return datetime.datetime.now().strftime('%Y%m%d')
current_date = get_current_date()
# create a new log file
new_log_file = os.path.join(log_dir, f'{log_file}_{current_date}')
os.system(f'touch {new_log_file}')
with open(os.path.join(log_dir, log_file), 'r') as f:
for line in f:
match = re.match(r'\[(\d{2}/\w{3}/\d{4})', line)
if match:
date = datetime.datetime.strptime(match.group(1), '%d/%b/%Y')
if date.strftime('%Y%m%d') != current_date:
current_date = date.strftime('%Y%m%d')
new_log_file = os.path.join(log_dir, f'{log_file}_{current_date}')
os.system(f'touch {new_log_file}')
os.system(f'echo "{line.strip()}" >> {new_log_file}')
```
这个脚本的工作原理是,先读入原始的Nginx访问日志文件,然后逐行检查每一条日志记录是否需要分割到新的日志文件中。
具体的分割策略是,按照日志记录中的时间戳(比如 [31/Mar/2021:15:25:38 +0800])来判断该记录属于哪一天的日志文件,如果和当前处理的日志文件不同,则需要创建一个新的日志文件。如果已经存在这个日志文件,则直接将当前行的日志写入,否则就需要先创建这个日志文件,再写入日志。