在Alpine Linux中如何安装和配置logrotate

如何安装logrotate将Nginx服务器的日志进行轮换?
如何自动滚动,压缩nginx的日志?

在Alpine Linux中安装和配置logrotate

执行以下命令:

# apk add logrotate

配置

默认情况下,cron每天都会调用logrotate:

# cat /etc/periodic/daily/logrotate

输出示例:

#!/bin/sh
 
if [ -f /etc/conf.d/logrotate ]; then
	. /etc/conf.d/logrotate
fi
 
if [ -x /usr/bin/cpulimit ] && [ -n "$CPULIMIT" ]; then
	_cpulimit="/usr/bin/cpulimit --limit=$CPULIMIT"
fi
 
$_cpulimit /usr/sbin/logrotate /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0

默认的logrotate文件是/etc/logrotate.conf:

# cat /etc/logrotate.conf

输出示例:

# see "man logrotate" for details
# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones
create

# use date as a suffix of the rotated file
dateext

# exclude alpine files
tabooext + .apk-new

# uncomment this if you want your log files compressed
compress

# main log file
/var/log/messages {}

# apk packages drop log rotation information into this directory
include /etc/logrotate.d

# system-specific logs may be also be configured here.

让我们为nginx服务器创建一个配置文件:

# vi /etc/logrotate.d/nginx

内容如下:

/var/log/nginx/*.log {
	missingok
	sharedscripts
	postrotate
	  /etc/init.d/nginx --quiet --ifstarted reopen
	endscript
}

其中

  • /var/log/nginx/*。log处理/var/log/nginx /目录中的所有日志文件。
  • missingok遇到任何错误时,不要终止,继续处理下一个日志文件。
  • sharedscripts共享脚本,表示postrotate脚本将只运行一次(在压缩旧日志之后),而不是对每个日志文件都运行一次。
  • postrotate ... script/command ... endscript在压缩旧日志后运行此脚本。这里的配置是,重新打开nginx的日志文件。
日期:2020-03-23 08:03:53 来源:oir作者:oir