主配置文件位于 /etc/logrotate.conf
你可以在 /etc/logrotate.d/ 目录内 添加自己的 日志文件切割(这些文件会被 /etc/logrotate.conf读入),如
#/etc/logrotate.d/ballsrace
/opt/wc-minigame/app.log
{
daily
rotate 3
missingok
notifempty
copytruncate
compress
dateext
}
if your log file is not owner by root (say by user 'service'), then you should add extra line :
{
su service service
daily
/usr/sbin/logrotate -d -f /etc/logrotate.d/ballsrace
/usr/sbin/logrotate -f /etc/logrotate.d/ballsrace
cat /var/lib/logrotate.status
- 如果有报错: error: Ignoring xxxx because it is writable by group or others
- 这是因为你的 conf 文件没有设置正确的权限
chmod 644 <you conf file>
crontal job 文件可能位于:
/etc/crontab.
d/
daily/
hourly/
monthly/
weekly/
/var/spool/cron/<user>
# 列出当前 任务
# crontab -l
# 编辑 /var/spool/cron/root 文件,
# crontab -e
0 0 * * * /usr/sbin/logrotate -f /etc/logrotate.d/ballsrace &> /dev/null
maybe you want to use echo to append job to crontab file
(不同系统,可能文件位置不一样, apline: /etc/crontabs/root )
echo $'*/1\t*\t*\t*\t*\t/usr/sbin/logrotate...' >> xxxx
# daily 00:00
echo $'0\t0\t*\t*\t*\t/usr/sbin/logrotate ...' >> xxx
# daily 01:00
echo $'0\t1\t*\t*\t*\t/usr/sbin/logrotate ...' >> xxx
# restart crond
systemctl restart crond
- compress
- 通过gzip 压缩转储以后的日志
- copytruncate
- 用于还在打开中的日志文件,把当前日志备份并截断;是先拷贝再清空的方式,拷贝和清空之间有一个时间差,可能会丢失部分日志数据。
- create选项此时被忽略
- missingok
- 如果日志丢失,不报错继续滚动下一个日志
- notifempty
- 当日志文件为空时,不进行轮转
- dateext
- 使用当期日期作为命名格式
- sharedscripts
- 运行postrotate脚本,作用是在所有日志都轮转后统一执行一次脚本。如果没有配置这个,那么每个日志轮转后都会执行一次脚本
- 类似
app &> log.log
- 这类日志文件, logrotate 的 truncate 不能生效,需要 使用追加的方式
>>
- i.e.
app >> app.log 2>&1
- 这类日志文件, logrotate 的 truncate 不能生效,需要 使用追加的方式
- 需要发送 USE1 信号给 nginx master 进程重新打开日志文件
$ kill -USR1 `ps axu | grep "nginx: master process" | grep -v grep | awk '{print $2}'`
- 更多的,是使用
postrotate
{
...
sharedscripts
postrotate
[ -e /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
sharedscripts
The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated.
# setup.sh
APPNAME="hda"
CONF_FILE="${APPNAME}_logr.conf"
echo ... generate conf file: ${CONF_FILE}
cat > ${CONF_FILE}<<EOF
`pwd`/../logs/access.log
`pwd`/../logs/error.log
{
daily
rotate 5
missingok
notifempty
copytruncate
compress
dateext
}
EOF
echo ... copy conf to /etc/logrotate.d/
cp ${CONF_FILE} /etc/logrotate.d/${APPNAME}
echo .. add task
if grep -q `pwd`"/hda_task.sh" /var/spool/cron/root; then
echo "task already exists"
else
echo "add new task"
# echo $'0\t0\t*\t*\t*\t/usr/sbin/logrotate -f /etc/logrotate.d/'${APPNAME}' &> /dev/null' >> /var/spool/cron/root
echo $'0\t0\t*\t*\t*\t/usr/bin/sh '`pwd`"/hda_task.sh"' &> /dev/null' >> /var/spool/cron/root
fi
echo ... restart crond
/bin/systemctl restart crond
echo ... end
#!/bin/sh
# hda_task.sh
echo run hda logrotate
/usr/sbin/logrotate -f /etc/logrotate.d/hda
kill -USR1 `ps axu | grep "nginx: master process" | grep -v grep | awk '{print $2}'`