logrotate 是 linux 系統用來分割日誌的系統工具,能夠方便將日誌按週期(日,周,月)和大小進行分割。javascript
當咱們的服務器訪問量比較大時,服務器的 access.log 可能會 G/天的級別增加,而咱們但願日誌能夠按天周月或當日志文件大小達到某個限額時進行分割。html
列舉下如何使用它對 apache 或 nginx 日誌進行切分:java
apache 其實自身已經集成了一個叫 rotatelogs 的工具,就在 apache 安裝目錄的 bin 下面,能夠很方便的進行日誌切割規則設置,在你的配置文件或者虛擬主機配置中以下設置linux
#年月日時分秒 1G大小分割 ErrorLog "|/usr/local/apache/bin/rotatelogs /var/log/httpd/error_log_%Y%m%d%H%M%S 1024M" #年月日 1G大小 CustomLog "|/usr/local/apache/bin/rotatelogs /var/log/httpd/access_log_%Y%m%d 1024M" common #年月日 每86400秒 即1天分割一次 480 爲時區的偏移量 北京東八區 60 * 8 = 480 s CustomLog "|/usr/local/apache/bin/rotatelogs /var/log/httpd/access_log_%Y%m%d 86400 480" common
/etc/logrotate.conf 主配置文件nginx
# see "man logrotate" for details # rotate log files weekly 以周做爲週期 weekly # keep 4 weeks worth of backlogs 保留4個分割文件 rotate 4 # create new (empty) log files after rotating old ones 建立新的日誌文件 create # use date as a suffix of the rotated file 以日期爲後綴 dateext # uncomment this if you want your log files compressed 默認不壓縮 #compress # RPM packages drop log rotation information into this directory 自定義日誌分割配置 nginx 的放這就好 include /etc/logrotate.d # no packages own wtmp and btmp -- we'll rotate them here /var/log/wtmp { monthly create 0664 root utmp minsize 1M rotate 1 } /var/log/btmp { missingok monthly create 0600 root utmp rotate 1 } # system-specific logs may be also be configured here.
默認配置如上apache
/etc/logrotate.d/* 獨立配置文件服務器
咱們能夠將自定義的日誌分割配置放在此處,會被加載進入主配置文件中,好比咱們新建一個工具
/etc/logrotate.d/nginx 配置文件:post
nginx的默認日誌目錄是 /home/wwwlogs/,默認pid目錄是/usr/local/nginx/logs/nginx.pid 這些須要根據本身的配置作相應調整。this
/home/wwwlogs/*.log { daily #以天爲週期分割日誌 minsize 1024M #最小 好比每日分割 但若是大小未到 1024M 則不分割 maxsize 2048M #最大 當日志文件超出 2048M 時,即使再下一個時間週期以前 日誌也會被分割 rotate 7 #保留七天 missingok #忽略錯誤 notifempty #若是文件爲空則不分割 not if empty dateext #以日期爲單位 size 1024M #以大小爲限制作日誌分割 size 會覆蓋分割週期配置 1024 1024k 1024M 1024G sharedscripts #開始執行附加的腳本命令 nginx寫日誌是按照文件索引進行的 必須重啓服務才能寫入新日誌文件 postrotate if [ -f /usr/local/nginx/logs/nginx.pid ]; then kill -USR1 `cat /usr/local/nginx/logs/nginx.pid` #重啓nginx服務 fi endscript }
我本身用的,一個日誌文件按1G大小分割
/home/wwwlogs/*.log { rotate 7 missingok notifempty dateext size 1024M sharedscripts postrotate if [ -f /usr/local/nginx/logs/nginx.pid ]; then kill -USR1 `cat /usr/local/nginx/logs/nginx.pid` #重啓nginx服務 fi endscript }
/etc/cron.daily/logrotate 每日任務
cron.daily 是 crond 的一個每日任務,天天凌晨零點執行一次
/usr/sbin/logrotate -dv 來開啓debugger詳情模式來查看配置是否正確
例如檢測全局
/usr/sbin/logrotate -dv /etc/logrotate.conf
檢測nginx配置
/usr/sbin/logrotate -dv /etc/logrotate.d/nginx
強制執行
/usr/sbin/logrotate -fv /etc/logrotate.d/nginx
一、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.
日誌文件權限問題,在相應的配置中設置以下配置就好 root 組的 root 用戶,本身作相應的權限聲明便可
#su user group su root root
OK,具體的用法能夠 man logrotate 一下!