安装logrotate

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默认切割日志的方式改成了按天切割。

posted on 2021-04-09 15:45  巨象  阅读(366)  评论(0编辑  收藏  举报