Nginx 配置access.log日志格式以及日志按天分割

在Nginx的使用过程中,如果不对Nginx的日志做自定义的配置的话,那么默认的access.log日志默认就只有这么一个日志文件,随着系统使用时间越来越就,日志文件就会越来越大,而且默认的日志记录的格式也不方便分析。所以我们在实际使用Nginx的过程中需要对其日志做一些配置。
http配置块中进行配置,也可以在每个server块中配置不同的access_log用以区分

  1. http{
  2. # 定义一个变量来存储年月日
  3. map $time_iso8601 $date {
  4. default "date-not-found";
  5. '~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
  6. }
  7. # 定义一个变量来存储时分秒
  8. map $time_iso8601 $time {
  9. default "time-not-found";
  10. '~T(?<hms>\d{2}:\d{2}:\d{2})' $hms;
  11. }
  12. # 定义日志格式为json格式
  13. log_format json_format '{
  14. "timestamp": "$date $time",
  15. "remote_addr": "$remote_addr",
  16. "remote_user": "$remote_user",
  17. "request": "$request",
  18. "status": "$status",
  19. "body_bytes_sent": "$body_bytes_sent",
  20. "http_referer": "$http_referer",
  21. "http_user_agent": "$http_user_agent",
  22. "http_x_forwarded_for": "$http_x_forwarded_for"
  23. },';
  24. # 定义一个变量来存储年月,可用来作为access.log的日志文件名,按月自动分割日志
  25. map $time_iso8601 $logmonth {
  26. '~^(?<ym>\d{4}-\d{2})' $ym;
  27. default 'date-not-found';
  28. }
  29. # 定义一个变量来存储年月日,可用来作为access.log的日志文件名,按天自动分割日志
  30. map $time_iso8601 $logdate {
  31. '~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
  32. default 'date-not-found';
  33. }
  34. # 开启access.log日志,可设置日志名变量(这里选择上面的按天)以便分割日志;可设置日志格式,以便更直观分析日志
  35. access_log logs/access-$logdate.log json_format;
  36. }

配置完需重启Nginx服务,如果发现没对应日志文件生成,看是否是 logs目录没有写入的权限,可以分配权限后再看一下。
分配权限:chmod 777 logs


© 2020-2025 www.chenhuazhan.com All Rights Reserved 备案号:桂ICP备17004487号-1 粤公网安备44030002005146