在Nginx的使用过程中,如果不对Nginx的日志做自定义的配置的话,那么默认的access.log日志默认就只有这么一个日志文件,随着系统使用时间越来越就,日志文件就会越来越大,而且默认的日志记录的格式也不方便分析。所以我们在实际使用Nginx的过程中需要对其日志做一些配置。
在http
配置块中进行配置,也可以在每个server块中配置不同的access_log用以区分
http{
# 定义一个变量来存储年月日
map $time_iso8601 $date {
default "date-not-found";
'~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
}
# 定义一个变量来存储时分秒
map $time_iso8601 $time {
default "time-not-found";
'~T(?<hms>\d{2}:\d{2}:\d{2})' $hms;
}
# 定义日志格式为json格式
log_format json_format '{
"timestamp": "$date $time",
"remote_addr": "$remote_addr",
"remote_user": "$remote_user",
"request": "$request",
"status": "$status",
"body_bytes_sent": "$body_bytes_sent",
"http_referer": "$http_referer",
"http_user_agent": "$http_user_agent",
"http_x_forwarded_for": "$http_x_forwarded_for"
},';
# 定义一个变量来存储年月,可用来作为access.log的日志文件名,按月自动分割日志
map $time_iso8601 $logmonth {
'~^(?<ym>\d{4}-\d{2})' $ym;
default 'date-not-found';
}
# 定义一个变量来存储年月日,可用来作为access.log的日志文件名,按天自动分割日志
map $time_iso8601 $logdate {
'~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
default 'date-not-found';
}
# 开启access.log日志,可设置日志名变量(这里选择上面的按天)以便分割日志;可设置日志格式,以便更直观分析日志
access_log logs/access-$logdate.log json_format;
}
配置完需重启Nginx服务,如果发现没对应日志文件生成,看是否是 logs目录没有写入的权限,可以分配权限后再看一下。
分配权限:chmod 777 logs