Linux系统日志切分工具LogRotate配置

Summary: Author: 张亚飞 | 阅读时间: 1 minute read | Published: 2019-12-03
Filed under Categories: LinuxTags: Note,

使用 LogRotate 切割 Nginx 日志

在 K8s 集群使用普通用户 nginx 启动 Nginx 服务后,发现过一段时间 Nginx 启动失败,报日志权限错误

nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (13: Permission denied)
2019/12/03 09:58:18 [warn] 1#1: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:2
2019/12/03 09:58:18 [alert] 1#1: detected a LuaJIT version which is not OpenResty's; many optimizations will be disabled and performance will be compromised (see https://github.com/openresty/luajit2 for OpenResty's LuaJIT or, even better, consider using the OpenResty releases from https://openresty.org/en/download.html)
2019/12/03 09:58:18 [emerg] 1#1: open() "/var/log/nginx/access.log" failed (13: Permission denied)

查看日志文件,发现 /var/log/nginx/access.log/var/log/nginx/error.log 日志文件的用户组为 www-data:adm,与默认启动的 nginx:nginx 不一致:

/var/log/nginx

Tue Dec 03 09:37:52 coam@a.us.1:/var/log/nginx$ ls -al
-rw-r-----  1 www-data adm         0 Nov 27 06:25 access.log
-rw-r-----  1 nginx    nginx  716344 Dec  2 16:28 access.log.1
-rw-r-----  1 nginx    nginx   29576 Nov 26 17:04 access.log.2.gz
-rw-r-----  1 nginx    nginx   41643 Nov 20 21:25 access.log.3.gz
-rw-r-----  1 www-data adm         0 Nov 27 06:25 error.log
-rw-r-----  1 nginx    nginx   58903 Dec  2 15:11 error.log.1
-rw-r-----  1 nginx    nginx    6478 Nov 26 16:33 error.log.2.gz
-rw-r-----  1 nginx    nginx    1945 Nov 21 06:21 error.log.3.gz

经查发现是系统定时备份服务 LogRotate 在创建的,查看 Nginx 配置文件:

/etc/logrotate.d/nginx

/var/log/nginx/*.log {
	daily
	missingok
	rotate 14
	compress
	delaycompress
	notifempty
	create 0640 www-data adm
	sharedscripts
	prerotate
		if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
			run-parts /etc/logrotate.d/httpd-prerotate; \
		fi \
	endscript
	postrotate
		invoke-rc.d nginx rotate >/dev/null 2>&1
	endscript
}

修改用户组并重启 LogRotate 服务解决问题

create 0640 nginx nginx

也可以通过以下命令修改:

sed -i 's/www-data adm/nginx nginx/' /etc/logrotate.d/nginx

Reference

日志集中化收集(二):logrotate 配置 使用logrotate切割nginx日志

Comments

Cor-Ethan, the beverage → www.iirii.com