nginx日志切割

一、法一:mv

1、vim  nginx_log.sh

#!/bin/bash
log_path=/var/log/nginx
path=/var/zjz.log(切割后的日志存放路径)
date=`date '+%Y-%m-%d-%H:%M:%S'`

/bin/mv ${log_path}/access.log    ${path}/access.$date.log
/bin/mv ${log_path}/error.log       ${path}/error.$date.log

# send a signal
/bin/kill -USR1 `ps axu | grep "nginx: master process" | grep -v grep | awk '{print $2}'`

二、法二:logrotate

logrotate 是Linux系统日志文件管理工具。用来把旧的日志文件删除,并创建新的日志文件,我们把它叫做“转储”。

可以根据日志文件的大小,也可以根据其天数来转储,这个过程一般通过 cron 程序来执行。

logrotate 程序还可以用于压缩日志文件,以及发送日志到指定的E-mail。

默认的logrotate被加入cron的/etc/cron.daily中作为每日任务执行。

/etc/logrotate.conf 主配置文件

/etc/logrotate.d/* 子配置文件(会被主配置读取)

1、# vim /etc/logrotate.d/nginx (配置轮转规则)

 /var/log/nginx/*.log {
        daily
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 640 nginx nginx
        sharedscripts
        postrotate
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}

2、手动轮转

# /usr/sbin/logrotate   -s /var/lib/logrotate/logrotate.status   /etc/logrotate.conf (-s 指定状态文件)

# grep 'nginx '     /var/lib/logrotate/logrotate.status //记录所有日志文件最近轮转的时间    

# grep 'nginx' /var/lib/logrotate/logrotate.status
"/var/log/nginx/error.log" 2019-9-14-1:0:0            //如果没有轮转过,第一次只有记录
"/var/log/nginx/access.log" 2019-9-16-0:2:39

3、查看轮转后日志存放位置

# cd /var/log/nginx/
# ls
access.log  access.log-20190915.gz  access.log-20190916  error.log

4、如何测试logrotate程序执行的情况

# /usr/sbin/logrotate -d /etc/logrotate.d/nginx
reading config file /etc/logrotate.d/nginx
Allocating hash table for state file, size 15360 B
Handling 1 logs
rotating pattern: /var/log/nginx/*.log  after 1 days (52 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/nginx/access.log
  log does not need rotating (log has been already rotated)considering log /var/log/nginx/error.log
  log does not need rotating (log is empty)not running postrotate script, since no logs were rotated

三、计划任务

1、系统级

# crontab -l   (列出所有系统级计划任务)
0 0 * * * /bin/bash /root/scripts/nginx_log.sh
0 4 * * * /bin/bash /root/scripts/nginx_log.sh

# crontab -e  (创建计划任务)

  *  *  9  *  *       /usr/sbin/logrotate   -s /var/lib/logrotate/logrotate.status   /etc/logrotate.conf

2、用户级计划任务

# cat  /var/spool/cron/root (root用户会和系统级同步)

0 0 * * * /bin/bash /root/scripts/nginx_log.sh
0 4 * * * /bin/bash /root/scripts/nginx_log.sh

3、删除计划任务

# crontab    -r  (删除所有)

You have new mail in /var/spool/mail/root

crontab   -r   Remove   all    jobs   for   the   current   users.(指定用户)

 

https://mp.weixin.qq.com/s/ET-NZD_V47efDhntQr1-nQ   logrotate 详解附带脚本

 

posted @ 2019-09-14 16:50  凡人半睁眼  阅读(692)  评论(0编辑  收藏  举报