久久青草精品A片狠狠,日韩欧美视频一区二区,亚洲国码AV日韩,国产精品黄在

Linux使用logrotate來切割日志文件

2017-05-04 17:25:33 362

程序在運行的時候為了了解運行狀態,會輸出日志文件,時間久了日志文件會變得非常大,甚至達到GB級別。我在golang應用里使用logrus包來打日志,配置和使用都很方便,就是沒有日志分割的功能,應用在線上運行一個月后日志文件都已經達到上百兆。后來發現了logrotate,這是centos自帶的日志分割工具,都不用安裝額外組件就能實現定時分割日志。

1.運行原理

logrotate由系統的cron運行,位置在/etc/cron.daily/logrotate

?

1
2
3
4
5
6
7
#!/bin/sh
/usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
 /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0

可以看到入口配置文件是/etc/logrotate.conf,依次運行/etc/logrotate.conf.d里的配置文件 如果發現配置的logrotate沒有執行,可以看下系統的crond服務有沒有開啟

2.配置

如果有安裝nginx,可以參考nginx里的配置例子

?

1
2
3
4
5
6
7
8
9
10
11
12
/var/log/nginx/*log {
 create 0644 nginx nginx
 daily
 rotate 10
 missingok
 notifempty
 compress
 sharedscripts
 postrotate
  /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
 endscript
}

第一行定義的是日志文件的路徑,可以用*通配,一般可以定義成*.log來匹配所有日志文件。也可以指定多個文件,用空格隔開,比如

?

1
2
3
/var/log/nginx/access.log /var/log/nginx/error.log {
  
}

花括號里面是日志切割相關的參數,下面是常用的切割參數

  1. compress 是否開啟壓縮,壓縮格式gzip

  2. 不開啟壓縮

  3. compresscmd 自定義壓縮命令

  4. compressexty 壓縮文件名后綴

  5. compressoptions 壓縮選項

  6. copy 復制一份文件

  7. create 后面跟mode owner group,設置新日志文件的權限

  8. daily 按天分割

  9. weekly 按周分割

  10. monthly 按月分割

  11. rotate 后面跟數字,表示需要保留的文件歷史記錄,超過數量就會刪除,或者通過郵件發送

  12. size 后面跟文件大小,比如100k、100M,超過這個大小后分割

  13. missingok 忽略不存在的文件,不報錯

  14. notifempty 不分割空文件

  15. sharedscripts 配合postrotate、prerotate,讓他們只執行一次

  16. postrotate/endscript 文件分割完后,執行postrotate、endscript之間的命令

  17. prerotate/endscript 文件分割完前,執行prerotate、endscript之間的命令

下面看幾個例子

?

1
2
3
4
5
6
7
8
9
/var/log/httpd/error.log {
 rotate 5
 mail i@wuyuans.com
 size=100k
 sharedscripts
 postrotate
  /sbin/killall -HUP httpd
 endscript
}

切割/var/log/httpd/error.log日志文件,超過100k后切割,保留最新的5個歷史記錄,超過5個的郵件發送到fss@qq.com,postrotate里的的命令是為了讓httpd重新打開日志文件。

?

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        /var/lib/mysql/mysqld.log {
         # create 600 mysql mysql
         notifempty
         daily
         rotate 3
         missingok
         compress
         postrotate
         # just if mysqld is really running

        提交成功!非常感謝您的反饋,我們會繼續努力做到更好!

        這條文檔是否有幫助解決問題?

        非常抱歉未能幫助到您。為了給您提供更好的服務,我們很需要您進一步的反饋信息:

        在文檔使用中是否遇到以下問題: