为了防止nginx日志日积月累变得很大而不方便查看管理,我们需要用logrotate对nginx的日志按照日期进行归档,以备查看分析nginx的访问记录等信息。

编辑/etc/logrotate.conf文件

   
   
   
   
  1. # see "man logrotate" for details  
  2. # rotate log files weekly  
  3. daily  
  4.  
  5. # keep 4 weeks worth of backlogs  
  6. rotate 4  
  7.  
  8. # create new (empty) log files after rotating old ones  
  9. create  
  10.  
  11. # use date as a suffix of the rotated file  
  12. dateext  
  13.  
  14. # uncomment this if you want your log files compressed  
  15. #compress  
  16.  
  17. # RPM packages drop log rotation information into this directory  
  18. include /etc/logrotate.d  
  19.  
  20. # no packages own wtmp and btmp -- we'll rotate them here  
  21. /var/log/wtmp {  
  22.     monthly  
  23.     create 0664 root utmp  
  24.     minsize 1M  
  25.     rotate 1  
  26. }  
  27.  
  28. /var/log/btmp {  
  29.     missingok  
  30.     monthly  
  31.     create 0600 root utmp  
  32.     rotate 1  
  33. }  
  34. # system-specific logs may be also be configured here.  

创建一个nginx文件

   
   
   
   
  1. # ll /etc/logrotate.d/nginx  
  2. -rw-r--r-- 1 root root 246 4月   5 20:09 /etc/logrotate.d/nginx  

增加以下内容

   
   
   
   
  1. /usr/local/nginx/logs/*.log {  
  2.     daily  
  3.     rotate 31  
  4.     missingok  
  5.     notifempty  
  6.     nocompress  
  7.     postrotate  
  8.         /bin/kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid 2>/dev/null) 2>/dev/null || :  
  9.     endscript  

强制生成一次日志信息

   
   
   
   
  1. logrotate -f /etc/logrotate.conf 

查看生产的日志,发现日志已经切割了