logrotate 是 linux 系统用来分割日志的系统工具,能够方便将日志按周期(日,周,月)和大小进行分割。javascript
当咱们的服务器访问量比较大时,服务器的 access.log 可能会 G/天的级别增加,而咱们但愿日志能够按天周月或当日志文件大小达到某个限额时进行分割。html
列举下如何使用它对 apache 或 nginx 日志进行切分:java
apache 其实自身已经集成了一个叫 rotatelogs 的工具,就在 apache 安装目录的 bin 下面,能够很方便的进行日志切割规则设置,在你的配置文件或者虚拟主机配置中以下设置linux
#年月日时分秒 1G大小分割 ErrorLog "|/usr/local/apache/bin/rotatelogs /var/log/httpd/error_log_%Y%m%d%H%M%S 1024M" #年月日 1G大小 CustomLog "|/usr/local/apache/bin/rotatelogs /var/log/httpd/access_log_%Y%m%d 1024M" common #年月日 每86400秒 即1天分割一次 480 为时区的偏移量 北京东八区 60 * 8 = 480 s CustomLog "|/usr/local/apache/bin/rotatelogs /var/log/httpd/access_log_%Y%m%d 86400 480" common
/etc/logrotate.conf 主配置文件nginx
# 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.
默认配置如上apache
/etc/logrotate.d/* 独立配置文件服务器
咱们能够将自定义的日志分割配置放在此处,会被加载进入主配置文件中,好比咱们新建一个工具
/etc/logrotate.d/nginx 配置文件:post
nginx的默认日志目录是 /home/wwwlogs/,默认pid目录是/usr/local/nginx/logs/nginx.pid 这些须要根据本身的配置作相应调整。this
/home/wwwlogs/*.log { daily #以天为周期分割日志 minsize 1024M #最小 好比每日分割 但若是大小未到 1024M 则不分割 maxsize 2048M #最大 当日志文件超出 2048M 时,即使再下一个时间周期以前 日志也会被分割 rotate 7 #保留七天 missingok #忽略错误 notifempty #若是文件为空则不分割 not if empty dateext #以日期为单位 size 1024M #以大小为限制作日志分割 size 会覆盖分割周期配置 1024 1024k 1024M 1024G sharedscripts #开始执行附加的脚本命令 nginx写日志是按照文件索引进行的 必须重启服务才能写入新日志文件 postrotate if [ -f /usr/local/nginx/logs/nginx.pid ]; then kill -USR1 `cat /usr/local/nginx/logs/nginx.pid` #重启nginx服务 fi endscript }
我本身用的,一个日志文件按1G大小分割
/home/wwwlogs/*.log { rotate 7 missingok notifempty dateext size 1024M sharedscripts postrotate if [ -f /usr/local/nginx/logs/nginx.pid ]; then kill -USR1 `cat /usr/local/nginx/logs/nginx.pid` #重启nginx服务 fi endscript }
/etc/cron.daily/logrotate 每日任务
cron.daily 是 crond 的一个每日任务,天天凌晨零点执行一次
/usr/sbin/logrotate -dv 来开启debugger详情模式来查看配置是否正确
例如检测全局
/usr/sbin/logrotate -dv /etc/logrotate.conf
检测nginx配置
/usr/sbin/logrotate -dv /etc/logrotate.d/nginx
强制执行
/usr/sbin/logrotate -fv /etc/logrotate.d/nginx
一、because parent directory has insecure permissions (It's world writable or writable by group which is not "root") Set "su" directive in config file to tell logrotate which user/group should be used for rotation.
日志文件权限问题,在相应的配置中设置以下配置就好 root 组的 root 用户,本身作相应的权限声明便可
#su user group su root root
OK,具体的用法能够 man logrotate 一下!