logrotate配置nginx日志切割


nginx默認的切割日志方式感覺不大好,現在介紹下如何實現每天23:59時按天切割日志。

ogrotate 是 linux 系統用來分割日志的系統工具,可以方便將日志按周期(日,周,月)和大小進行分割。

當我們的服務器訪問量比較大時,服務器的 access.log 可能會 G/天的級別增長,而我們希望日志可以按天周月或當日志文件大小達到某個限額時進行分割。

logrotate工具

/etc/logrotate.conf 主配置文件

# 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.

默認配置如上

/etc/logrotate.d/* 獨立配置文件

我們可以將自定義的日志分割配置放在此處,會被加載進入主配置文件中,比如我們新建一個

/etc/logrotate.d/nginx 配置文件:

 nginx的默認日志目錄是 /home/wwwlogs/,默認pid目錄是/usr/local/nginx/logs/nginx.pid 這些需要根據自己的配置做相應調整。

第一種方法:

修改/etc/logrotate.d/nginx文件,如下:

/var/log/nginx/*.log {
    daily   #按天切割日志
    missingok #忽略錯誤
    rotate 14 #保留14個文件
    compress  #壓縮文件
    delaycompress #延遲一天壓縮文件
    dateext #以日期為單位 默認-%Y%m%d
    notifempty #空文件不切割
    create 0640 www-data adm #創建 0640權限的日志文件
    sharedscripts
    prerotate
        if [ -d /etc/logrotate.d/httpd-prerotate ]; then
            run-parts /etc/logrotate.d/httpd-prerotate;
             fi
    endscript
    postrotate
        if [ -f /run/nginx.pid ]; then
                        kill -USR1 `cat /run/nginx.pid` #切割日志完成后通知nginx重新打開日志文件,不終止nginx
                fi
    endscript
}

然后,修改/etc/crontab 中的#######行,將25 6 改成59 23,如下:

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab' # command to install the new version when you edit this file # and files in /etc/cron.d. These files also have username fields, # that none of the other crontabs do. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 17 * * * * root cd / && run-parts --report /etc/cron.hourly 25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ) ####### 47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly ) 52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly ) #

但是,這樣修改影響很大,建議第二種方式

第二種方式:

1、在/etc下創建logrotate.daily.0文件夾,移動文件:

mv /etc/logrotate.d/nginx /etc/logrotate.daily.0/ # 具體配置內容參照上文

2、執行

sudo crontab -e

3、執行

#nginx log logrotate
59 23 * * * /usr/sbin/logrotate -f /etc/logrotate.daily.0/nginx >/dev/null 2>&1

這樣,之前nginx默認切割日志的方式改成了按天切割。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM