https://blog.csdn.net/weixin_30470643/article/details/98077260
https://www.cnblogs.com/yyxianren/p/10843065.html
https://www.cnblogs.com/canflyfish/p/11568588.html
如果任由訪問日志寫下去,日志文件會變得越來越大,甚至是寫滿磁盤。
所以,我們需要想辦法把日志做切割,比如每天生成一個新的日志,舊的日志按規定時間刪除即可。
實現日志切割可以通過寫shell腳本或者系統的日志切割機制實現。
shell腳本切割Nginx日志
切割腳本內容: #!/bin/bash logdir=/var/log/nginx #定義日志路徑 prefix=`date -d "-1 day" +%y%m%d` #定義切割后的日志前綴 cd $logdir for f in `ls access.log` do mv $f $f-$prefix #把日志改名 done /bin/kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid 2>/dev/null) 2>/dev/null #生成新的日志 bzip2 *$prefix #壓縮日志 find . -type f -mtime +180 |xargs /bin/rm -f #刪除超過180天的老日志
示例:
#!/bin/bash logdir=/usr/local/nginx/logs/ prefix=`date -d "-1 day" +%y%m%d` cd $logdir for f in `ls access.log` do mv $f $prefix-$f done /bin/kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid 2>/dev/null) 2>/dev/null find . -type f -mtime +180 |xargs /bin/rm -f
系統日志切割機制
在/etc/logrotate.d/下創建nginx文件,內容為: /data/logs/access.log { daily rotate 30 missingok notifempty compress sharedscripts postrotate /bin/kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid 2>/dev/null) 2>/dev/null || : endscript } 說明: nginx日志在/data/logs/目錄下面,日志名字以log結尾 daily表示每天切割 rotate 30表示日志保留30天 missingok表示忽略錯誤 notifempty表示如果日志為空,不切割 compress表示壓縮 sharedscripts和endscript中間可以引用系統的命令 postrotate表示當切割之后要執行的命令
附:
1.如何測試logrotate程序執行的情況
答:/usr/sbin/logrotate -d /etc/logrotate.d/nginx
2.怎么查看log文件的具體執行情況
答:cat /var/lib/logrotate/status
3.使用-v或-d參數時,顯示log does not need rotating
答:logrotate在對status未記錄的文件進行轉儲時,會在status添加一條該文件的記錄,並將操作時間設為當天。之后程序再次對此文件進行轉儲時發現這個文件今天已經操作過,就不再進行相關操作。
解決方法:
1. vi /var/lib/logrotate/status 更改相對應的文件操作日期
2. 使用-s指定狀態文件
3.分割日志時報錯:error: skipping "/var/log/nginx/test.access.log" because parent directory has insecure permissions (It's world writable or writable by group which is not "root") Set "su" directive in config file to tell logrotate which user/group should be used for rotation.
答:添加“su root list”到/etc/logrotate.d/nginx文件中即可
如下:
/var/log/nginx/*.log {
su root list
daily
missingok
rotate 52
compress
delaycompress
notifempty
#ifempty
create 0640 www-data adm
sharedscripts
postrotate
[ ! -f /var/run/nginx.pid ] || kill -USR1 `cat /var/run/nginx.pid`
endscript
}