实现nginx日志切割,优化短视频源码日志文件管理

发布来源:云豹科技
发布人:云豹科技
2022-09-29 10:03:14

短视频源码搭建的时候,通常会搭建Nginx服务,它拥有体积小、性能高、速度高等优点,但是也存在缺点,不能自动切割其产生的访问日志文件就是缺点之一。

当短视频源码的用户访问量提升,将会产生大量的日志文件,如果不能进行切割的话,不便于文件管理,所以今天我们就来说一下nginx怎样实现日志切割。

一、配置

1、基本配置

如果短视频源码有安装nginx,可以参考nginx里的配置例子:


/var/log/nginx/*log {
 create 0644 nginx nginx
 daily
 rotate 10
 missingok
 notifempty
 compress
 sharedscripts
 postrotate
  /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
 endscript
}


第一行定义的是日志文件的路径,可以用*通配,一般可以定义成*.log来匹配所有日志文件,也可以指定多个文件,用空格隔开,比如:


/var/log/nginx/access.log /var/log/nginx/error.log {
 
}


2、常用参数

上面语句的花括号里面是日志切割相关的参数,下面是常用的切割参数

compress 是否开启压缩,压缩格式gzip

不开启压缩

compresscmd 自定义压缩命令

compressexty 压缩文件名后缀

compressoptions 压缩选项

copy 复制一份文件

create 后面跟mode owner group,设置新日志文件的权限

daily 按天分割

weekly 按周分割

monthly 按月分割

rotate 后面跟数字,表示需要保留的文件历史记录,超过数量就会删除,或者通过邮件发送

size 后面跟文件大小,比如100k、100M,超过这个大小后分割

missingok 忽略不存在的文件,不报错

notifempty 不分割空文件

sharedscripts 配合postrotate、prerotate,让他们只执行一次

postrotate/endscript 文件分割完后,执行postrotate、endscript之间的命令

prerotate/endscript 文件分割完前,执行prerotate、endscript之间的命令

二、相关范例

1、切割/var/log/httpd/error.log日志文件,超过100k后切割,保留最新的5个历史记录,超过5个的邮件发送,postrotate里的的命令是为了让httpd重新打开日志文件。


/var/log/httpd/error.log {
 rotate 5
 mail i@wuyuans.com
 size=100k
 sharedscripts
 postrotate
  /sbin/killall -HUP httpd
 endscript
}


2、这是对短视频源码mysql日志的切割,每天一份,忽略空文件,保留最新3份,使用gzip压缩。


/var/lib/mysql/mysqld.log {
 # create 600 mysql mysql
 notifempty
 daily
 rotate 3
 missingok
 compress
 postrotate
 # just if mysqld is really running
 if test -x /usr/bin/mysqladmin && \
 /usr/bin/mysqladmin ping &>/dev/null
 then
 /usr/bin/mysqladmin --local flush-error-log \
    flush-engine-log flush-general-log flush-slow-log
 fi
 endscript
}


三、Logrotate定时任务


[root@test ~]# cat /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日志切割,避免手动切割。

声明:以上内容为云豹科技原创,未经作者本人同意,禁止转载,否则将追究相关法律责任www.yunbaokj.com

声明:
以上内容为云豹科技作者本人原创,未经作者本人同意,禁止转载,否则将追究相关法律责任