天天看點

linux 日志按大小切割_Linux使用logrotate來切割日志檔案

程式在運作的時候為了了解運作狀态,會輸出日志檔案,時間久了日志檔案會變得非常大,甚至達到GB級别。我在golang應用裡使用logrus包來打日志,配置和使用都很友善,就是沒有日志分割的功能,應用線上上運作一個月後日志檔案都已經達到上百兆。後來發現了logrotate,這是centos自帶的日志分割工具,都不用安裝額外元件就能實作定時分割日志。

1.運作原理

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

#!/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裡的配置例子

/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來比對所有日志檔案。也可以指定多個檔案,用空格隔開,比如

/var/log/nginx/access.log /var/log/nginx/error.log { }

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

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

不開啟壓縮

compresscmd 自定義壓縮指令

compressexty 壓縮檔案名字尾

compressoptions 壓縮選項

copy 複制一份檔案

create 後面跟mode owner group,設定新日志檔案的權限

daily 按天分割

weekly 按周分割

monthly 按月分割

rotate 後面跟數字,表示需要保留的檔案曆史記錄,超過數量就會删除,或者通過郵件發送

size 後面跟檔案大小,比如100k、100M,超過這個大小後分割

missingok 忽略不存在的檔案,不報錯

notifempty 不分割空檔案

sharedscripts 配合postrotate、prerotate,讓他們隻執行一次

postrotate/endscript 檔案分割完後,執行postrotate、endscript之間的指令

prerotate/endscript 檔案分割完前,執行prerotate、endscript之間的指令

下面看幾個例子

/var/log/httpd/error.log { rotate 5 mail [email protected] size=100k sharedscripts postrotate /sbin/killall -HUP httpd endscript }

切割/var/log/httpd/error.log日志檔案,超過100k後切割,保留最新的5個曆史記錄,超過5個的郵件發送到[email protected],postrotate裡的的指令是為了讓httpd重新打開日志檔案。

/var/lib/mysql/mysqld.log { # create 600 mysql mysql notifempty daily rotate 3 missingok compress postrotate # just if mysqld is really running if test -x /usr/bin/mysqladmin && /usr/bin/mysqladmin ping &>/dev/null then /usr/bin/mysqladmin --local flush-error-log flush-engine-log flush-general-log flush-slow-log fi endscript }

這是對mysql日志的切割,每天一份,忽略空檔案,保留最新3份,使用gzip壓縮

/home/wuyuan/log/*.log { su wuyuan wuyuan create 0777 wuyuan wuyuan daily rotate 10 olddir /home/wuyuan/log/old missingok postrotate endscript nocompress }

這是我在用的配置項,對log目錄所有.log檔案切割,每天一份,保留10份,新檔案設定權限777,曆史檔案保留在old目錄裡,這樣可以友善檢視。因為應用程式用的logrus使用append的方式寫日志,是以不需要重新打開日志檔案,這點logrus做得很不錯。

3.測試

寫完配置檔案後可以手動執行下,來驗證是否可用。

logrotate -f /etc/logrotate.d/wuyuan

其中-f 表示強制執行,其他指令可以用help來檢視

logrotate --help 用法: logrotate [OPTION...] -d, --debug Don't do anything, just test (implies -v) -f, --force Force file rotation -m, --mail=command Command to send mail (instead of `/bin/mail') -s, --state=statefile Path of state file -v, --verbose Display messages during rotation -l, --log=STRING Log file --version Display version information Help options: -?, --help Show this help message --usage Display brief usage message

沒問題的話日志就會被移到old目錄下,并帶上日期,之前的log檔案會被清空

以上就是本文的全部内容,希望對大家的學習有所幫助,也希望大家多多支援腳本之家。