前言
最近在做项目时,代理端用到了nginx,按照nginx的通常配置来说,日志会生成在./logs下面的access.log和error.log文件中,对一般的小体量程序来说,采用一个文件来对存储所有的日志足够了,但对于tps>20的项目来说,随着acces.log的体量越来越大,排查和分析问题成了难点,也不利于nginx的性能提升。所以,日志切割存储成为了必要选择。
网上对nginx日志按天存储的方式主要有三种方式,一是采用脚本,写定时任务进行切割;二是通过一些三方工具实现;三是通过修改nginx.conf文件实现。直接说我是采用第三种方式实现的,因为第一二种方式觉得比较麻烦,有感兴趣的可以自行百度,这里我就不叙述了。
优点:通过简单的配置conf文件即可实现。
缺点:每天生成的日志都是按日期生成的,例如access-20211123.log,对于在nginx上配置了需要读取access.log文件的监控或其他脚本的,需要修改脚本。
nginx.conf文件修改实现日志分割的方法:
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
map $time_iso8601 $logdate {
'~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
default 'date-not-found';
}
access_log XX/nginx/access-$logdate.log main;#这里填你nginx日志的文件目录
open_log_file_cache max=10;
}
或者:
if不能用在http作用域中。
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
server {
if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})") {
set $year $1;
set $month $2;
set $day $3;
}
access_log /var/log/nginx/access-$year-$month-$day.log;#这里填你nginx日志的文件目录
open_log_file_cache max=10;
}
$time_iso8601 是内嵌变量用来获取时间,获取的时间格式如下:2020-08-21T16:01:02+02:00。于是我们使用正则表达式来获取所需时间的详细数据。
大功告成,亲测有效!感谢Nginx 日志按天生成 | 程序员技术之旅提供的思路。