Nginx / httpd 日志轮询及压缩保存天数
一、日志需求
Apache、Nginx、MariaDB的访问日志及访问错误日志,默认是保存在一个指定的文件内。
如果访问量很大,文件会变的很大,影响的日志写入的速度及备份。
因此需要对Apache、Nginx、MariaDB的日志进行按日分割并进行压缩,压缩日志保存30天(可根据需要调节)
二、解决方案
使用cron 和 logrotate 来管理日志文件
1. 编写nginx的logrotate配置文件,并将文件放到/etc/logrotate.d/目录下,权限0644(读写/读/读)
# ll /etc/logrotate.d/ -rw-r--r-- 1 root root 194 Apr 12 21:50 httpd -rw-r--r-- 1 root root 868 Aug 17 18:12 mysql -rw-r--r-- 1 root root 255 Sep 20 08:29 nginx -rw-r--r-- 1 root root 203 Nov 6 2016 php-fpm -rw-r--r--. 1 root root 136 Jun 10 2014 ppp -rw-r--r--. 1 root root 224 Sep 8 2015 syslog -rw-r--r--. 1 root root 100 Jun 16 2015 wpa_supplicant -rw-r--r--. 1 root root 100 Dec 3 2015 yum
nginx 文件内容
vim /etc/logrotate.d/nginx
# nginx logrotate
#
# 默认配置详见 vim /etc/logrotate.conf
# weekly
# rotate 4
# create
# dateext
# #compress
#
# Author: mimvp.com
# create: 2017.09.01
# update: 2024.07.08
/usr/local/nginx/logs/*.log {
daily
rotate 30
create 0644 www www
dateext
size 100M
olddir /usr/local/nginx/logs/old_log
# compress
# delaycompress
missingok
notifempty
sharedscripts
postrotate
/bin/kill -USR1 `cat /usr/local/nginx/logs/nginx.pid 2>/dev/null` 2>/dev/null || true
endscript
}
配置参数说明:
/usr/local/nginx/logs/*.log nginx访问日志文件存放的目录,默认是所有.log文件
日志每天截断并压缩,保留30天的数据
错误信息忽略,空日志文件不转储
压缩的日志文件存储到指定的日志保存目录 /usr/local/nginx/logs/old_log
在日志截断后,kill进程后重启nginx,以便生成新的访问日志文件
httpd 文件内容
vim /etc/logrotate.d/httpd
/var/log/httpd/*.log {
daily
rotate 30
missingok
notifempty
compress
sharedscripts
olddir /var/log/httpd/old_log
postrotate
/bin/kill -HUP `cat /var/run/httpd.pid 2> /dev/null` 2> /dev/null || true
endscript
}
2. 确认 logrotate 运行正常
1)检查 logrotate主配置文件/etc/logrotate.conf
vim /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
# uncomment this if you want your log files compressed
#compress
# RPM packages drop log rotation information into this directory
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.
2) 确认/etc/cron.daily/下面有logrotate脚本
# ll /etc/cron.daily/ -rwxr-xr-x. 1 root root 332 Dec 3 2015 0yum-daily.cron -rwx------. 1 root root 180 Jul 31 2013 logrotate -rwxr-xr-x. 1 root root 618 Mar 18 2014 man-db.cron
3) 查看脚本内容 /etc/cron.daily/logrotate
vim /etc/cron.daily/logrotate
#!/bin/sh
/usr/sbin/logrotate /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
/usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0
参考推荐:
Nginx 使用 cron 和 logrotate 管理日志文件
LNMP(CentOS+Nginx+Mysql+PHP)服务器环境配置
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2024-07-10 17:27:44
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!
文章不错支持一下吧